DataTable中的数据导出到Excel
用Microsoft.Interop.Excel12.0导出数据,本地成功。但往往发布到IIS后,因为权限设置等问题,导出会失败。
后来网上搜到另外一种导出方法, 沿袭Gridview中的数据导出,倒也实用。
View Code
//将datatable中数据导入到execl中
private void DataTable3Excel(System.Data.DataTable dtData, String FileName)
{
System.Web.UI.WebControls.GridView dtExport = 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)
{
//设置编码和附件格式
//System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)作用是防止中文文件名乱码
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application nd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "GB2312";
//导出Excel文件
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
//为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView
dtExport = new System.Web.UI.WebControls.GridView();
dtExport.DataSource = dtData.DefaultView;
dtExport.AllowPaging = false;
dtExport.DataBind();
//下载到客户端
dtExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
Be the change you want to see in the world.