我的代码运行一个存储过程,为每个客户检索多个报告。所有这些报告都在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();
}
答案 0 :(得分:1)
首先使用 Nuget Package manager
安装EPPlus
EPPlus
然后将您的代码更改为此
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();
}
}
}
}