C#导出为Excel格式

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

我的问题:

在将数据导出到Excel文件后,我在下面的Excel表中有值,

导出的Excel表

美元

 50.0 35.0 40.0 60.0 etc.. 

如果ctrl ”并用鼠标点击 35.0和40.0,Excel 不能求和35.0和40.0,因为35.0是string显示“35.0”而40.0是string显示“40.0”

问题是关于总和选定的行,但我不能总结,因为值是string不是数字

如何通过C#代码在Excel表中删除“”string号?

谢谢。

删除引号改变这一行:

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

对此:

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

如果你不反对使用第三方库,有这个解决scheme: http : //www.codeproject.com/Articles/692092/A-free-Export-to-Excel-Csharp-class-using-OpenXML

它使用OpenXML库(可通过nuget获得)。

它的作用就像一个魅力 – 好吧,如果你的数据中只有整数和string。 它可以被定制,但是。 要查看的方法是WriteDataTableToExcelWorksheet(DataTable dt, WorksheetPart worksheetPart) ,您将不得不照顾不同的数据types( DoubleDecimalDateTime …)。 获取数字列的string值时,我也推荐使用number.ToString(CultureInfo.InvariantCulture) 。 否则会出现同样的问题:列不会被识别为正确的数字(最好是文本列,否则会出现错误)。

您还可以在列中设置数字的自定义格式(如果您确实需要使用特定格式的数字): http : //lateral8.com/articles/2010/6/11/openxml-sdk-20-formatting- Excel的values.aspx