PRivate void Dum
PExcel(GridView gv, string FileN
ame)
{//带格式导出
string style = @"<style> .text { mso-number-format:\@; } </style>";
Response.ClearContent();
Response.Charset = "GB2312";
Response.ContentEncoding =
System.Text.Encoding.UTF8;
Response.AddHeader("content-dispos
ITion", "attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
Ht
MLTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
// Style is added dynam
ically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}
p
ublic
override void VerifyRenderin
ginServerForm(Control control)
{
}
此外,变量style的作用是控制GridView列的样式,避免发生excel表中字符前导0被当成数字给截掉这样的问题, 通过Response.Write方法将其添加到输出流中。最后把样式添加到ID列。这一步需要在RowDataBound事件中完成:
1protected void gvUsers_RowDataBound(object sender, GridViewRowEvent
args e)
{
if (e.Row.RowType
== DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
}