[英]C# Export to Excel format
的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是字符串顯示“35.0”而40.0是字符串顯示“40.0” 。
問題是關於總和選定的行但是我不能求和,因為值是字符串而不是數字
如何通過C#代碼刪除Excel表格中的“”字符串?
謝謝。
要刪除引號,請更改此行:
strLawTable.Append("<th style=\"text-align: right\">=\"" + GetExcellFormatString(Currency.USD) + "\"</th>");
^^remove ^^remove
對此:
strLawTable.Append("<th style=\"text-align: right\">=" + GetExcellFormatString(Currency.USD) + "</th>");
如果您不反對使用第三方庫,可以使用以下解決方案: http : //www.codeproject.com/Articles/692092/A-free-Export-to-Excel-Csharp-class-using-OpenXML
它使用OpenXML庫(可通過nuget獲得)。
它就像一個魅力 - 好吧,如果您的數據中只有整數和字符串。 但它可以定制。 要查看的方法是WriteDataTableToExcelWorksheet(DataTable dt, WorksheetPart worksheetPart)
,您必須處理不同的數據類型( Double
, Decimal
, DateTime
...)。 在獲取數字列的字符串值時,我還建議使用number.ToString(CultureInfo.InvariantCulture)
。 否則會出現同樣的問題:列不會被識別為正確的數字(最好是文本列,或者單元格中會出錯)。
您還可以在列中設置數字的自定義格式(如果您確實需要使用特定的數字格式): http : //lateral8.com/articles/2010/6/11/openxml-sdk-20-formatting- Excel的values.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.