Asp.net开发时经常用到的功能,导出数据到Excel表中保存
/// <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();
}
}
/// <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();
}
}
本文介绍了一种使用ASP.NET将数据从DataTable导出到Excel的方法。通过DataGrid渲染和HTTP上下文响应来实现Excel文件的下载。适用于需要批量导出数据的应用场景。


877

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



