我想将GridView中的数据导出到Excel中,一个纯净的.xls文件。
我在网上搜到的方法实际上是导出了一个 html 格式文件再把文件名后缀欺骗性地写成了 .xls ,它将GridView中的格式都原样输出了。改怎么导出一个正真的表格?
下面是我的代码:
protected void Button2_Click(object sender, EventArgs e)
{
if (gvInfo.Rows.Count > 0)
{
//调用导出方法
ExportGridViewForUTF8(gvInfo, DateTime.Now.ToShortDateString() + ".xls");
}
else
{
// obo.Common.MessageBox.Show(this, "没有数据可导出,请先查询数据!");
}
}
private void ExportGridViewForUTF8(GridView GridView, string filename)
{
string attachment = "attachment; filename=" + filename;
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", attachment);
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
以下是我导出后的表格:
