asp.net将内容导出到Excel,Table表格数据(html)导出EXCEL

时间:2023-02-03 07:20:51

代码:

   

      /// <summary>
/// HTML Table表格数据(html)导出EXCEL
/// </summary>
/// <param name="tableHeader">表头</param>
/// <param name="tableContent">内容</param>
/// <param name="sheetName">文件名称</param>
public void ExportToExcel(string tableHeader,string tableContent,string sheetName)
{
string fileName = sheetName + DateTime.Now.ToString("yyyyMMddHHmmss");
string tabData = htmlTable;
if (tabData != null)
{
StringWriter sw = new System.IO.StringWriter();
sw.WriteLine("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
sw.WriteLine("<table>");
sw.WriteLine("<tr style=\"background-color: #e4ecf7; text-align: center; font-weight: bold\">");
sw.WriteLine(tableHeader);
sw.WriteLine("</tr>");
sw.WriteLine(tableContent);
sw.WriteLine("</table>");
sw.WriteLine("</body>");
sw.WriteLine("</html>");
sw.Close();
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
//Response.Charset = "GB2312";
//this.EnableViewState = false;
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.Write(sw);
Response.End();
}
}