之前网上查找了很多关于这类的代码。要不是中文乱码,要不是就是太复杂。这个是我用过最好用的。
//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);//数据的dsDataGrid 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();
}