将DataTable导出是常见的需求,可以调用以下几种类方法进行导出。
1.适用于web的字符流导出方式
private static void DataTableToExcel(DataTable dt, string saveName)
{
DataGrid dgExcel = new DataGrid();
dgExcel.DataSource = dt;
dgExcel.DataBind();
HttpContext.Current.Response.Charset = "GB2312";
string fileName = HttpUtility.UrlEncode(saveName, System.Text.Encoding.UTF8);
string str = "attachment;filename=" + fileName + ".xls";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("content-disposition", str);
//如需添加其他标头或新增自定义行
//StringWriter sw_title = new StringWriter();
//HtmlTextWriter htmlTextWriter_title = new HtmlTextWriter(sw_title);
//htmlTextWriter_title.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "20px");//样式
//Label label1 = new Label();
//label1.Text = "在原有DataDable上新增标头 自定义行";
//label1.RenderControl(htmlTextWriter_title);
StringWriter sw = new StringWriter();
HtmlTextWriter htmTextWriter = new HtmlTextWriter(sw);
dgExcel.RenderControl(htmTextWriter);
HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=utf-8\"/>" + sw.ToString());
HttpContext.Curren