【发布时间】:2015-05-20 20:01:13
【问题描述】:
我的网站中有 6 个网格视图需要导出到 excel,但每个都在一张不同的表格中。
此链接Export GridView to multiple Excel sheet 使用了非常相似的东西,但他使用的是数据集,而我没有。我是 C# 新手,所以我无法更改它以适应我的解决方案。
我的代码将所有网格视图导出到同一张表。我创建了一个循环来运行我的gridviews,现在我需要为每个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 自动化的建议:support.microsoft.com/en-us/kb/257757?wa=wsignin1.0 你最好寻找第三方工具来执行 Excel 导出,或者您可以将 Excel 导出作为计划作业运行,以便稍后发送给用户(取决于您的需要)。
-
@maniak1982:发布的代码不使用互操作。
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
@John Saunders:maniak1982 是对的。我在之前的代码中使用了 Interop。解决方法如下。
-
在您发布的代码中,您在哪里使用了 Interop?我只看到一个 GridView。