在Web中GridView导出EXCEL:移除控件和定义样式应用
public static void GridViewToExcel(GridView grd, HttpResponse response, string charset) {
RemoveControls(grd);
response.Clear();
response.Buffer = true;
response.Charset = charset;
response.AppendHeader("Content-Disposition", "attachment;filename=NewFileName.xls"); //文件名可以自定义
response.ContentEncoding = System.Text.Encoding.UTF8;
response.ContentType = "application/ms-excel";
System.Globalization.CultureInfo AreaInfo = new System.Globalization.CultureInfo("zh-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(AreaInfo);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//可选:定义样式
oStringWriter.WriteLine(Styles());
grd.GridLines = GridLines.Both;
grd.Font.Name = "Arial";
grd.HeaderStyle.Font.Bold = true;
grd.RenderControl(oHtmlTextWriter);
response.Write(oStringWriter.ToString());
response.End();
}
//样式可以在EXCEL中设置好后,另存为HTML来确定
private static string Styles(){
return "<style>td{mso-number-format:\"\\@\";}.dateTime{mso-number-format:\"h\\:mm\"}</style>";
}
//如GridView的CheckBox,Button,TextBox等等
private static void RemoveControls(Control gv)
{
Literal replace = new Literal();
for (int i = 0; i < gv.Controls.Count; i++){
if (gv.Controls[i].GetType() == typeof(CheckBox)){
replace.Text = ((CheckBox)gv.Controls[i]).Checked ? "Y" : "N";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, replace);
}
if (gv.Controls[i].HasControls()){
RemoveControls(gv.Controls[i]);
}
}
}