前几天做项目需要用到将GridView中的数据导入到Excel,原以为很简单,上网搜了一下资料,果然方法不少,于是就采用了一个:

 private void GridViewToExcel()
{
Response.Clear();
Response.BufferOutput = true;
//设定输出的字符集
Response.Charset = "GB2312";

//假定导出的文件名为FileName.xls
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//设置导出文件的格式
Response.ContentType = "application/vnd.ms-excel";
//关闭ViewState
EnableViewState = false;
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
GridView1.RenderControl(textWriter);
//把HTML写回浏览器
Response.Write(stringWriter.ToString());
Response.End();
}

引用此方法:

 protected void btnToExcel_Click(object sender, EventArgs e)
{
//直接导出Excel
GridViewToExcel();
}

原以为这样就可以了,但是我的Excel是2007版的,使用以上的方法会弹出一个提示:

将GridView导入到Excel

感觉很郁闷啊!!
网上资料说,由于使用Web方法并不是真正的打开Excel,而是把页面html转换成Excel,在office2003版本里不会出现问题,但是在office2007里就不行了。
一般解决这样的问题最好是使用第三方控件:MyXls和NOPI。

相关文章:

  • 2022-02-10
  • 2021-06-01
  • 2021-11-16
  • 2022-12-23
  • 2022-01-14
  • 2021-09-05
  • 2021-06-28
  • 2022-12-23
猜你喜欢
  • 2021-12-08
  • 2021-11-11
  • 2021-12-03
  • 2021-06-23
  • 2021-10-13
  • 2021-11-25
相关资源
相似解决方案