将asp网格数据导出为ex​​cel

时间:2015-10-29 13:55:24

标签: c# asp.net .net gridview grid

我想将网格数据直接导出到Excel。

我试过" HtmlTextWriter"它允许我下载文件。但下载后我无法打开文件(Excel抛出错误,该文件格式不正确。)

我搜索并发现我需要先创建一个XML文件,然后才能导出到Excel。是这样吗?

或者我是否需要先将该文件保存在我的服务器上然后下载?

或者,如果我可以使用像ClosedXML这样的任何NuGet包,或者任何其他包都会有所帮助。

2 个答案:

答案 0 :(得分:0)

点击按钮

尝试以下代码
protected void btn_excel_Click(object sender, ImageClickEventArgs e)
{
    try
    {

        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            //To Export all pages
            GridView2.AllowPaging = false;
            work();   // in this function you can bind GridView2

            GridView2.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in GridView2.HeaderRow.Cells)
            {
                cell.BackColor = GridView2.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in GridView2.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = GridView2.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = GridView2.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";
                }
            }

            GridView2.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }
    catch (Exception ex)
    {

    }

}

答案 1 :(得分:0)

最简单的方法是从Nuget获取ClosedXML,然后获取要导出到数据表中的数据,然后使用下面的代码

XLWorkbook wb = new XLWorkbook();
DataTable dt = GetDataTableOrWhatever();
wb.Worksheets.Add(dt,"WorksheetName");