前几天做项目需要用到将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(); }
以上方法还不能真正实现功能,还需参考:
http://www.cnblogs.com/XACOOL/p/5663778.html
http://www.cnblogs.com/XACOOL/p/5663767.html