时间:2021-07-01 10:21:17 帮助过:26人阅读
输出流中。最后把样式添加到ID列。这一步需要在RowDataBound事件中完成:
private void DumpExcel(GridView gv, string FileName)
{//带格式导出
string style = @"<style> .text { mso-number-format:\@; } </style>";
Response.ClearContent();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
上面的行17的重载函数是必须的,否则会报“GridView要在有run=server的From体内”的错。
此外,变量style的作用是控制GridView列的样式,避免发生excel表中字符前导0被当成数字给截掉这样的问题, 通过Response.Write方法将其添加到
1protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
}