dataset导出成excel

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

//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();

}

 

你可能感兴趣的:(Excel)