asp.net Html table Render to Excel

今天遇到了这个问题,记录下来,方便不知道的朋友以后用,当在生成Excel表格时直接将网页表格直接保存成excel文件后,用excel能打开表格中的数字自动用科学计数法表示了,比如table中的0.0在excel中显示为0。

解决方案如下。

   protected void downloadButton_Click(object sender, EventArgs e)
    {
        BindPage();

        Response.ClearContent();
        string attachment = "attachment; filename=Payroll.xls";
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        tabData.Border = 1;
        tabData.RenderControl(htw);
        string startHtml = "<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\">";
        string endHtml = "</html>";
        Response.Write(startHtml + sw.NewLine + sw.ToString().Replace("<td align=\"right\" style=\"80px;\">","<td align=\"right\" style=\"80px;\" x:str>") + endHtml);
        Response.End(); 
    }
原文地址:https://www.cnblogs.com/gaotianle/p/1718064.html