如何防止将某些html导出到Excel文件时缺少css
本文关键字:文件 Excel css 何防止 html | 更新日期: 2023-09-27 18:36:22
我使用以下代码成功地将 html 表导出到 excel 文件
public void exportGridToExcel(Control ctl)
{
string attachment = "attachment; filename=etrack_excel_export.xls";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
ctl.RenderControl(htextw);
HttpContext.Current.Response.Write(stw.ToString());
HttpContext.Current.Response.End();
}
问题是导出后我应用于表格的所有css在excel文件中都丢失了,如何防止css丢失?
我终于得到了该怎么做!我与任何有相同问题的人分享:
string attachment = "attachment; filename=etrack_excel_export.xls";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
ctl.RenderControl(htextw);
HttpContext.Current.Response.Write(stw.ToString());
FileInfo fi = new FileInfo(Server.MapPath("../Content/Styles/StyleSheet.css"));
System.Text.StringBuilder sb = new System.Text.StringBuilder();
StreamReader sr = fi.OpenText();
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
sr.Close();
Response.Write("<html><head><style type='text/css'>" + sb.ToString() + "</style></head>" + stw.ToString() + "</html>");
stw = null;
htextw = null;
Response.Flush();
Response.End();