我已导出到excel代码,该代码从数据库获取数据,然后创建动态gridview,然后将该数据导出为excel。
问题是我的表格与我提到的文件名相同。那么我该如何更改工作表名称
这是我正在使用的代码
GridView gridView = new GridView();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "SummaryReport " + Helper.GetTime(DateTime.UtcNow).ToString() + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
gridView.DataSource = ReportExecutor.ReportExportData(startDate, endDate);
gridView.DataBind();
//This will change the header background color
gridView.HeaderRow.Style.Add("background-color", "#FFFFFF"); //
//This will apply style to gridview header cells
for (int index = 0; index < gridView.HeaderRow.Cells.Count; index++)
{
gridView.HeaderRow.Cells[index].Style.Add("background-color", "#778899"); //Light Slate Gray
gridView.HeaderRow.Cells[index].Style.Add("foreground-color", "#ffffff"); // White
}
int index2 = 1;
//This will apply style to alternate rows
foreach (GridViewRow gridViewRow in gridView.Rows)
{
gridViewRow.BackColor = Color.White;
if (index2 <= gridView.Rows.Count)
{
if (index2 % 2 != 0)
{
for (int index3 = 0; index3 < gridViewRow.Cells.Count; index3++)
{
gridViewRow.Cells[index3].Style.Add("background-color", "#e6e6fa");// Lavender
}
}
}
index2++;
}
gridView.RenderControl(htmlTextWriter);
//// Response.Write(style);
Response.Write(stringWriter.ToString());
Response.End();
答案 0 :(得分:0)
我担心您无法更改通过将Response内容类型设置为excel而生成的excel文件的工作表名称。请参阅SO question和ASP.NET forum
的已接受答案您还可以查看EPPlus,其中包含在代码中编辑工作表名称的选项。
答案 1 :(得分:0)
无法使用StringWriter。您可能需要重新打开,然后在使用StringWriter成功编写工作表后重命名工作表。
否则,您必须使用备用方法来创建Excel。这是一个例子