How to prevent css missing when exporting some html to excel file?

Deadly 提交于 2019-12-23 01:58:08

问题


I am exporting an html table to excel file successfully using following code

    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();
    }

The issue is that after exportation all css I have applied to the table is missing in the excel file , How can I prevent the css from missing?


回答1:


I finally got what to do ! I share It with anyone who has the same issue :

        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();


来源:https://stackoverflow.com/questions/19487944/how-to-prevent-css-missing-when-exporting-some-html-to-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!