您的位置:首页 > 其它

传入一个table,文件名,导出Excel的方法

2010-11-25 15:13 525 查看
/// <summary>
/// 将DataTable 导出为EXCEL,并直接提供下载
/// </summary>
/// <param name="ds">需要导处的DataTable</param>
/// <param name="fileName">到处生成的文件名</param>
///
public bool ExportExcelByDataTable(DataTable dt, string fileName)
{

try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-7";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");

HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DataGrid dg = new DataGrid();
dg.HeaderStyle.CssClass = "dgHead";
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);

HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls");
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
HttpContext.Current.Response.End();
return true;
}
catch
{
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: