C#导出到excel

时间:2014-12-23 11:53:34

标签: c# excel export

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

我的问题:

我的客户更改了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中的任何内容,我只需要解决方案。

感谢。

1 个答案:

答案 0 :(得分:1)

更改此行

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

as:

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

在&lt; \ th&gt;

之前和之后注意= \“和\”