net3.5 Gridview 数据导出到Excel
我用的是VS2008开发的,我电脑上安装的Excel是2007版。网上也有相关的代码,但应用到我程序中出现错误:
如导出文件名是乱码:
打开时提示错误:
我的相关代码如下:
public static void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName+".xls");
// HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Output.Write(tw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
帮我看看哪里有问题?大家有更适用代码的可以分享?
------解决方案--------------------参考
C# code
public static void DataTable2Excel(System.Data.DataTable dtData)
{
System.Web.UI.WebControls.DataGrid dgExport = null;
// 当前对话
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
// IO用于导出并返回excel文件
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
// 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
curContext.Response.Charset = "";
// 导出excel文件
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
// 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
dgExport = new System.Web.UI.WebControls.DataGrid();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
// 返回客户端
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
}
------解决方案--------------------
度娘,Myxls
你这个导出局限性太大!