我有一个gridview,它在运行时添加了多个标题,如下面的snap中所示:
我想将此gridview中的数据导出到excel,我有以下代码:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
gdView.HeaderRow.BackColor = Color.White;
foreach (TableCell hcell in gdView.HeaderRow.Cells)
{
hcell.BackColor = Color.White;
}
foreach (GridViewRow row in gdView.Rows)
{
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.CssClass = "textmode";
}
}
}
gdView.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();
}
}
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
// controller
}
我得到的excel输出如下:
正如您所看到的,标题行的颜色继续超出表格区域。此外,顶部标题行在Excel输出中折叠。
请大家好好建议如何解决这个问题。
感谢。
答案 0 :(得分:0)
我最终可以通过修改代码解决问题:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int x = 0; x <= 3; x++)
{
GridViewRow rows = (GridViewRow)gdView.HeaderRow.Parent.Controls[x];
rows.BackColor = Color.White;
rows.Height = 15;
for (int i = 0; i <= rows.Cells.Count - 1; i++)
{
rows.Cells[i].BackColor = Color.Maroon;
}
}
foreach (GridViewRow row in gdView.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.VerticalAlign = VerticalAlign.Middle;
cell.CssClass = "textmode";
}
}
gdView.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();
}
}
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
// controller
}