在mvc中导出时使用excel添加多个工作表

时间:2016-12-15 04:19:52

标签: c# asp.net-mvc asp.net-mvc-4 datatables

其实我想从dataTable导出一个excel文件。我设法做到了。但是,如何在从dataTable导出时在同一个excel文件中添加空表?

这是我的代码:

 public void ExportToExcel(DataTable dts)
    {
        if (dts.Rows.Count > 0)
        {
            string filename = "2.Dependent Master.xls";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dgGrid.DataSource = dts;
            dgGrid.DataBind();

            dgGrid.RenderControl(hw);

            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");

            Response.Write(tw.ToString());

            Response.End();
        }
    }

任何帮助表示赞赏。在此先感谢!!!!

1 个答案:

答案 0 :(得分:2)

您无法使用简单的HTML添加多个工作表。

而不是你可以使用Closed XML开源库

https://closedxml.codeplex.com/

样品

 var workbook = new XLWorkbook();
 var worksheet1 = workbook.Worksheets.Add(PassYourDatatable1);
 var worksheet2 = workbook.Worksheets.Add(PassYourDatatable2);

How to add Datatable to worksheet