mardi 21 janvier 2014

Générer un excel avec C#

   public void FichierExcel(List<BeanTelechargementAppelOffre> DemandesBeans)
        {


            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.Charset = "";
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" +"ListeEntreprises.xls" + "\"");

            Table tbl = new Table() { BorderWidth = new Unit(1) };
            TableHeaderRow th = new TableHeaderRow();
            th.Font.Bold = true;
            th.Cells.Add(new TableCell() { Text = "Liste des Personnes", ColumnSpan = 4, HorizontalAlign = HorizontalAlign.Center, BackColor = Color.DarkBlue, ForeColor = Color.White });
            tbl.Rows.Add(th);

            th = new TableHeaderRow();
            th.Font.Bold = true;

            th.Cells.Add(new TableCell() { Text = "Nom ou raison sociale", BackColor = Color.DarkBlue, ForeColor = Color.White, BorderWidth = new Unit(1) });
            th.Cells.Add(new TableCell() { Text = "Les pi&egrave;ces t&eacute;l&eacute;charg&eacute;es", BackColor = Color.DarkBlue, ForeColor = Color.White, BorderWidth = new Unit(1) });
            th.Cells.Add(new TableCell() { Text = "Email de la personne", BackColor = Color.DarkBlue, ForeColor = Color.White, BorderWidth = new Unit(1) });
            th.Cells.Add(new TableCell() { Text = "Date de la consultation", BackColor = Color.DarkBlue, ForeColor = Color.White, BorderWidth = new Unit(1) });

            tbl.Rows.Add(th);
            foreach (BeanTelechargementAppelOffre bean1 in DemandesBeans)
            {

                var tr = new TableRow();
                tr.Cells.Add(new TableCell() { Text = "" + bean1.NomPersonne, BorderWidth = new Unit(1) });
                tr.Cells.Add(new TableCell() { Text = bean1.TypeFichier, HorizontalAlign = HorizontalAlign.Center, BorderWidth = new Unit(1) });
                tr.Cells.Add(new TableCell() { Text = bean1.EmailPersonne, HorizontalAlign = HorizontalAlign.Center, BorderWidth = new Unit(1) });
                tr.Cells.Add(new TableCell() { Text = Convert.ToDateTime(bean1.DateConsultation).ToShortDateString(), HorizontalAlign = HorizontalAlign.Center, BorderWidth = new Unit(1) });
                tbl.Rows.Add(tr);
            }
            System.Text.StringBuilder stb = new System.Text.StringBuilder();
            System.IO.StringWriter sw = new System.IO.StringWriter(stb);
            HtmlTextWriter textWriter = new HtmlTextWriter(sw);
            tbl.RenderControl(textWriter);
            response.Write(stb.ToString());
            response.End();
        }

Aucun commentaire:

Enregistrer un commentaire