我在我的网站中有6个gridviews,我需要导出到excel,但每个都在一张不同的工作表中。将多个gridviews导出到多个excel选项卡(工作表)
此链接Export GridView to multiple Excel sheet使用的东西非常相似,但他使用的是数据集,而我不是。我是C#的新手,所以我无法改变它以适应我的解决方案。
我的代码将所有的gridviews导出到同一张表。我创建了一个循环来运行我的GridView,现在我需要将代码生成到每个Excel表单中。
protected void btExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FARPOP_Mensal_" + txDt.Text + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("Windows-1252");
Response.Charset = "ISO-8859-1";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView[] gvExcel = new GridView[] { gvAnual, gvPorUF, gvPorFarmacia, gvPorMunicipio, gvPorPV, gvPorCNPJ };
for (int i = 0; i < gvExcel.Length; i++)
{
GridView gv = gvExcel[i];
//
// Need to redirect to each sheet here?
//
gvExcel[i].HeaderRow.BackColor = Color.White;
gvExcel[i].UseAccessibleHeader = false;
gvExcel[i].AllowPaging = false;
for (int x = 0; x < gvExcel[i].Columns.Count; x++)
{
gvExcel[i].Columns[x].Visible = true;
}
gvExcel[i].DataBind();
foreach (TableCell cell in gvExcel[i].HeaderRow.Cells)
{
cell.BackColor = Color.CadetBlue;
cell.Enabled = false;
}
foreach (GridViewRow row in gvExcel[i].Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.Controls.Clear();
if (row.RowIndex % 2 == 0)
{
cell.BackColor = Color.White;
}
else
{
cell.BackColor = Color.LightBlue;
}
cell.CssClass = "textmode";
}
}
gvExcel[i].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();
}
}
在你进一步了解这个兔子洞之前,我想告诉你微软建议不要在服务器上使用Office Automation:https://support.microsoft.com/en-us/kb/257757? wa = wsignin1.0 您最好在寻找第三方工具来执行Excel导出,或者您可以将Excel导出作为计划作业运行,以便稍后(根据您的需要)发送给用户。 – maniak1982
@ maniak1982:发布的代码不使用Interop。 –
我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –