将多个数据网格导出到单个Excel文件上的不同工作表

时间:2014-01-29 08:05:25

标签: asp.net sql export-to-excel

我的代码运行一个存储过程,为每个客户检索多个报告。所有这些报告都在excel的同一张表中查看。有人可以告诉我如何在多个Excel工作表上查看我的报表,而不仅仅是1?

 using (SqlCommand sqlCmd = new SqlCommand("databases.dbo.SP_GetAll_Reports",    connection))
        {
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@customerName", SqlDbType.NVarChar).Value = custName;
            using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
            {
                Session["TaskTable"] = dt;
                sqlDa.Fill(dt);
                if (dt.Tables.Count > 0)
                {
                     StringWriter sw = new StringWriter();
                    foreach(DataTable table in dt.Tables)
                    {
                         HtmlTextWriter hw = new HtmlTextWriter(sw);
                        DataGrid dg = new DataGrid();
                        dg.DataSource = table;
                        dg.DataBind();
                        dg.RenderControl(hw);
                    }
                    Response.Clear();
                    Response.AddHeader("content-disposition", "attachchment;       filename=Report_Accounting.xls");
                    Response.Charset = "";
                    Response.ContentType = "application/vnd.xls";
                    Response.Write(sw.ToString());
                    Response.End();
                }

1 个答案:

答案 0 :(得分:1)

首先使用 Nuget Package manager

安装EPPlus
  1. 右键单击您的项目
  2. 选择 Nuget Package Manager
  3. 搜索EPPlus
  4. 点击安装
  5. 然后将您的代码更改为此

    using OfficeOpenXml;
    
    
     using (SqlCommand sqlCmd = new SqlCommand("databases.dbo.SP_GetAll_Reports",    connection))
     {
         sqlCmd.CommandType = CommandType.StoredProcedure;
         sqlCmd.Parameters.AddWithValue("@customerName", SqlDbType.NVarChar).Value = custName;
         using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
         {
             Session["TaskTable"] = dt;
             sqlDa.Fill(dt);
             if (dt.Tables.Count > 0)
             {
                 MemoryStream ms = new MemoryStream();
                 int i=1;
                 using (ExcelPackage package = new ExcelPackage(ms))
                 {
                     foreach(DataTable table in dt.Tables)
                     {
                         ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet"+i++);
                         worksheet.Cell["A1"].LoadFromDataTable(table, true); 
                     }
                     Response.Clear(); 
                     package.SaveAs(Response.OutputStream);
                     Response.AddHeader("content-disposition", "attachchment;       filename=Report_Accounting.xls");
                     Response.Charset = "";
                     Response.ContentType = "application/vnd.xls";
                     Response.End();
                 }
             }
         }
     }