asp.net通过拼接html导出excel
核心代码:
/// <summary> /// 拼接Html方式导出Excel /// </summary> /// <param name="ds">需要下载的Dataset数据</param> /// <param name="fileName">下载文件名</param> public void TBExportExcel(DataSet ds, string fileName) { StringBuilder sb = new StringBuilder(); sb.Append("<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>"); sb.Append("<head><title></title><meta http-equiv='Content-Type' content=\"text/html; charset=gb2312\"></head>"); sb.Append("<body>"); //构建表 sb.Append("<table x:str cellpadding='0' cellspacing='0' border='1px' rules='all' id='T_Code' style='border-collapse:collapse;' mce_style='border-collapse:collapse;'>"); //构建标题 sb.Append("<tr>"); foreach (DataColumn dc in ds.Tables[0].Columns) { sb.AppendFormat("<th>{0}</th>", dc.ColumnName); } sb.Append("</tr>"); DataRowCollection rows = ds.Tables[0].Rows; foreach (DataRow dr in rows) { sb.Append("<tr>"); sb.AppendFormat("<td>{0}</td>", dr["标题"]); sb.AppendFormat("<td>{0}</td>", dr["值"]); sb.AppendFormat("<td>{0}</td>", dr["时间"]); sb.AppendFormat("<td>{0}</td>", dr["备注"]); sb.Append("</tr>"); } sb.Append("</table></body></html>"); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; System.Web.HttpContext.Current.Response.Charset = "GB2312"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); System.Web.HttpContext.Current.Response.Write(sb.ToString()); System.Web.HttpContext.Current.Response.End(); }