2017-08-11 67 views
0

除了將數字保留爲數字外,我的代碼正常工作。如果語句在我調試時捕獲到double值。然而,我不能寫入數據類型,除了字符串到Excel。如果我應該更精確,Excel中的單元格是正確的,但它們不是數字。使用C#中的Open Xml SDK將DataTable導出到Excel時保留數據類型

foreach (System.Data.DataRow dsrow in table.Rows) 
{ 
    DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row(); 
    foreach (String col in columns) 
    { 
     DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell(); 

     if (dsrow[col].GetType() == typeof(Double)) 
     { 
      cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number; 

     } 
     else 
     { 
      cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String; 
     } 

     cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); // 

     newRow.AppendChild(cell); 
    } 

    sheetData.AppendChild(newRow); 
} 
+0

[的Office Open XML SDK號碼寫入到表(可能的重複https://stackoverflow.com/questions/16607063/office-open-xml -sdk-writing-numbers-to-sheet) – Kyra

+0

正如我剛剛在數字的情況下報告爲重複的問題的答案中可以看到的,首先將該值放入數據類型中,然後更改數據類型。否則,你仍然使用'ToString'方法將它作爲一個字符串 – Kyra

回答

0

我一直在努力解決同樣的問題。 看來如果您使用逗號作爲小數點分隔符的語言環境,則會出現問題。在XML中,它應該是美式格式。

因此,在指定的ToString工作CutureInfo我:

var dataRow = new Row(); 
var cell = new Cell(); 
cell.CellValue = new CellValue(1.234.ToString(new CultureInfo("en-US"))); 
cell.DataType = CellValues.Number; 
dataRow.AppendChild(cell); 
sheetData.AppendChild(dataRow);