2014-12-23 152 views
3

的ActionResult:C#導出爲Excel格式

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表格如下,

Ex移植的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」

的問題是關於和所選行,但是我不能因爲求和值的字符串不是數字

如何刪除「」出串號在Excel表格中的C#代碼?

謝謝。

+1

如果嘗試使用另一個小數點分隔符'''而不是'.',會怎樣? –

+0

我必須說。任何解決方案,請 – Richard

+1

爲什麼不只是從你的字符串中刪除引號?更改'strLawTable.Append(「 = \」「+ GetExcellFormatString(Currency.USD)+」\「」); (「 =」+ GetExcelFormatString(Currency。USD)+「」);' – chancea

回答

1

要刪除引號改變這一行:

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

對此:

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

如果你不反對使用第三方庫,有這樣的解決方案: http://www.codeproject.com/Articles/692092/A-free-Export-to-Excel-Csharp-class-using-OpenXML

它採用OpenXML庫(可通過的NuGet)。

它的作用就像一個魅力 - 好吧,如果你的數據中只有整數和字符串。不過,它可以定製。要看的方法是WriteDataTableToExcelWorksheet(DataTable dt, WorksheetPart worksheetPart),您需要處理不同的數據類型(DoubleDecimalDateTime ...)。獲取數字列的字符串值時,我也推薦使用number.ToString(CultureInfo.InvariantCulture)。否則會出現同樣的問題:列不會被識別爲正確的數字(最好是文本列,否則會出現錯誤)。

您還可以設置號碼的自定義格式在您的列(如果你真的要使用你的號碼特定的格式):http://lateral8.com/articles/2010/6/11/openxml-sdk-20-formatting-excel-values.aspx