C#导出到excel

标签 c# excel export

Action 结果:

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

GetExcelFormatString 方法:

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

我的问题:

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

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

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

我可以使用return fileActionResult 中的任何东西,我只需要解决方案。

谢谢。

最佳答案

改变这一行

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

作为:

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

注意 <\th> 前后的 =\"和\"

关于C#导出到excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27619834/

相关文章:

c# - Esc pos 打印条形码

c# - 为什么不能使用 is 运算符来区分 bool 和 Nullable<bool>?

excel - 如何防止 Excel 将包含冒号的字符串处理为公式

java - 如何使用 Apache POI 选择和加粗整个工作表

export - 编写 Microsoft Project 文件

Java Eclipse : How to view Compile warnings

c# - 带有LoadAsync()的Query()不会返回实体,尽管它应该

c# - 如何获取XML中元素属性的值

c# - 保存/创建/导出 Excel 工作表时出现 OutOfMemoryException

mysql - 如果我们将表导出到另一个数据库中,那么它的所有触发器也会随之导出吗?