·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> dataset导出成excel

dataset导出成excel

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

之前网上查找了很多关于这类的代码。要不是中文乱码,要不是就是太复杂。这个是我用过最好用的。

//ds为数据源,filename为保存的文件名
publicvoidCreateExcel(DataSet ds,stringFileName)
{
//设置信息
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType="application/vnd.ms-excel";
HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.Charset="GB2312";
//保存的文件名
HttpContext.Current.Response.AddHeader("content-disposition","attachment;filename="+HttpUtility.UrlEncode(FileName));
//保存excel的文件流
StringWriter stringWrite =newStringWriter();
HtmlTextWriter htmlWrite =newHtmlTextWriter(stringWrite);
//数据的ds
DataGrid dg =newDataGrid();
dg.DataSource= ds;
dg.DataBind();
dg.RenderControl(htmlWrite);
//输出数据
HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>"+ stringWrite.ToString());
HttpContext.Current.Response.End();
}