C# Export to excell

本文关键字:excell to Export | 更新日期: 2023-09-27 18:35:02

ActionResult:

var strLawTable = new StringBuilder();
    strLawTable.Append("<thead>");
    strLawTable.Append("<tr>");
    strLawTable.Append("<th style='"text-align: right'">Dollar</th>");
    strLawTable.Append("</tr>");
    strLawTable.Append("</thead>");   
strLawTable.Append("<tbody>");
foreach (Currency currency in Model.List)
{
strLawTable.Append("<tr>");
strLawTable.Append("<th style='"text-align: right'">" + GetExcellFormatString(Currency.USD) + "</th>");
strLawTable.Append("</tr>");
}
strLawTable.Append("</tbody>");

string headerTable = "<table>" + strLawTable + "</table>";      
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=TestFile.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
System.IO.StringWriter sw = new System.IO.StringWriter();
sw.Write(headerTable);
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
Response.Write(sw.ToString());
Response.End();

GetExcellFormatString方法:

public string GetExcellFormatString(double doubleAmount) 
{
            if (doubleAmount < 1000)
                return doubleAmount.ToString("0.00");
            else if (doubleAmount < 1000000)
                return doubleAmount.ToString("0000.00");
            else if (doubleAmount < 1000000000)
                return doubleAmount.ToString("0000,000.00");
            else if (doubleAmount < 1000000000000)
                return doubleAmount.ToString("0000000000.00");
            else return doubleAmount.ToString();
}

我的问题:

我的客户更改了窗口上的区域设置,他们看到

 3.50 as "May50"
20.50 as "Apr15"
etc..

Excel格式在我的计算机上是正确的,但是在客户的计算机上,它始终显示日期文本。

我也在下面尝试过,但仍然有同样的问题

byte[] fileContents = Encoding.UTF8.GetBytes(headerTable);
return File(fileContents, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Test.xls");

尝试了很多解决方案(返回文件等(,我完全错过了,我需要添加什么?

我可以在ActionResult中使用return file或任何东西,我只需要解决方案。

谢谢。

C# Export to excell

更改此行

strLawTable.Append("<th style='"text-align: right'">" + GetExcellFormatString(Currency.USD) + "</th>");

如:

strLawTable.Append("<th style='"text-align: right'">='"" + GetExcellFormatString(Currency.USD) + "'"</th>");

请注意 <''th 之后和之前的 =''" 和 ''>