Export List to Excel

Asked

Viewed 454 times

0

I have a list and would like to export to Excel, in this code this bringing the records correctly, just do not export the file.

I need to add something else or I’d have another way?

CorpDAO dao = new CorpDAO();
        List<CorpCRM>  listaExport = dao.ListarCorp(produto, anomes, nome, matricula, pernumber);

        var listCarregaExcel = listaExport;
        DataGrid rptExcel = new DataGrid();
        rptExcel.DataSource = listCarregaExcel;
        rptExcel.DataBind();
        Response.Clear();
        Response.Buffer = true;
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");           
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("content-disposition", "attachment;filename=Relatório_lista.xls");
        Response.Charset = "";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        rptExcel.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        rptExcel = null;
        listCarregaExcel = null;
        Response.End();
  • what’s going wrong? what’s the error message?

1 answer

2

For webforms we use it here:

            using (var tw = new StringWriter())
            {
                using (var hw = new HtmlTextWriter(tw))
                {
                    var grid = new GridView();
                    grid.DataSource = RetornarDados();

                    grid.HeaderStyle.Font.Bold = true;
                    grid.DataBind();
                    grid.RenderControl(hw);

                    Response.Clear();
                    Response.AppendHeader("content-disposition", "attachment; filename=NOMEDOARQUIVO.xls");
                    Response.ContentType = "application/ms-excel";
                    Response.Charset = "utf-8";
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                    this.EnableViewState = false;
                    Response.Write(tw.ToString());
                    Response.End();
                }
            }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.