asp.net 将dt转换成excel 在线下载
1.方法
private StringWriter GetStringWriter(DataTable dt) { StringWriter sw = new StringWriter(); //读列名 foreach (DataColumn dc in dt.Columns) sw.Write(dc.ColumnName + "\t"); //读列值 //重新的一行 sw.Write(sw.NewLine); if (dt != null) { foreach (DataRow dr in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { sw.Write(dr[i].ToString() + "\t"); } sw.Write(sw.NewLine); } } sw.Close(); return sw; } protected void ExcelImport(DataTable dt, string ExportFileName) { StringWriter sw = GetStringWriter(dt); //当前编码 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //把输出的文件名进行编码 string fileName = HttpUtility.UrlEncode(ExportFileName, System.Text.Encoding.UTF8); //文件名 string str = "attachment;filename=" + fileName + ".xls"; //把文件头输出,此文件头激活文件下载框 HttpContext.Current.Response.AppendHeader("Content-Disposition", str);//http报头文件 HttpContext.Current.Response.ContentType = "application/ms-excel"; this.Page.EnableViewState = false; Response.Write(sw); Response.End(); }
2.调用
string sql = "select * from eco_sys_members "; DataTable dt = DbHelperSQL.Query(sql).Tables[0]; if (dt.Rows.Count > 0) { //导出Excel ExcelImport(dt, DateTime.Now.ToString()); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。