/// <summary>
/// 把datatable导入到excel中
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="defaultFileName">默认保存文件名</param>
public static void DataTableToExcel(DataTable dt, string defaultFileName)
{
DataGrid dgd = new DataGrid();
dgd.DataSource = dt.DefaultView;
dgd.DataBind();
if (dgd.Items.Count == 0)
{
throw (new Exception("there is no data in dataTable"));
}
else
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + defaultFileName);
//HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");
HttpContext.Current.Response.ContentEncoding = Encoding.UTF7;
//设置输出流为简体中文,试了GBK会出现乱码
HttpContext.Current.Response.ContentType = "application/ms-excel";
//设置输出文件类型为excel文件。
CultureInfo myCItrad = new CultureInfo("ZH-CN", true);
StringWriter oStringWriter = new StringWriter(myCItrad);
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
dgd.RenderControl(oHtmlTextWriter);
HttpContext.Current.Response.Write(oStringWriter.ToString());
HttpContext.Current.Response.End();
}
}

3181



被折叠的 条评论
为什么被折叠?



