GridView 中的数据导出到 Excel 方法(经测试完整)
protected void Button2_Click(object sender, EventArgs e)
...{
if (this.GridView1.Rows.Count == 0)
...{
Response.Write("<script>alert('没有查找到数据,无法导出!')");
}
else
...{
this.GridView1.AllowPaging = false; // 将有分页的 GridView 中的数据全部导出
到 Excel
gvBond();
export("application/ms-excel", "工作人员.xls");
// 换成 export("application/ms-word", "工作人员.doc"); 那么导出的就是 Word
格式的了.
this.GridView1.AllowPaging = true;
gvBond();
}
}
public void export(string FileType, string FileName)
...{
string style = @"<style>.text{mso-number-format:@}</script>";//导入到 excel 时,保存
表里数字列中前面存在的 0 .
PrepareGridViewForExport(Control gv)//将模版列显示出来
Response.Clear();
Response.Charset = "GB2312";
Response.ContentEncoding = Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
this.GridView1.AllowPaging = false;
System.Globalization.CultureInfo myCItrad = new
System.Globalization.CultureInfo("ZH-CN", true);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
this.GridView1.RenderControl(htw);
Response.Write(style);
Response.Write(sw.ToString());
//Response.Write(dt.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)