Export List to Excel

0

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

Do I need to add something else or would I 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();
    
asked by anonymous 04.11.2016 / 15:23

1 answer

2

For webforms we use this 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();
                }
            }
    
08.11.2016 / 11:49