簡體   English   中英

當全球化將逗號設置為小數點分隔符時,如何在 OpenXML Excel 單元格中存儲小數/雙精度

[英]How store decimal/doubles in OpenXML Excel cells when globalisation sets comma as decimal separator

I'm trying to create an Excel worksheet in C# in OpenXML, but end up with Excel having to "repair" the Workbook because of doubles have been stored with commas as decimal separators in the Excel /xl/worksheets/sheet1.xml file.

我的 Excel 和 Windows 全球化是瑞典語,每當雙精度轉換為字符串時,它將小數分隔符設置為逗號。

當我做一個

double d = 355d/113d;
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new Cell();
cell.CellValue = new CellValue(d);
cell.DataType = CellValues.Number;

實際存儲在 Excel 的 /xl/worksheets/sheet1.xml 中的是

<x:c s="4" t="n">
    <x:v>3,14159292035398</x:v>
</x:c>

用逗號作為小數分隔符。 這使我的瑞典語 Excel 強制“修復”並將單元格轉換為文本/字符串而不是數值。 我可以在 Excel 中以最小的努力手動轉換為數值,但這在此應用程序中是不可接受的。

在“修復”后查看 /xl/worksheets/sheet1.xml 並手動將字符串轉換為十進制值,它們存儲為

 <v>3.1415929203539825</v>

用點作為小數分隔符。 顯而易見的解決方案 - 所以我認為 - 是用點而不是像這樣的東西強制存儲我的十進制值

double d = 355d/113d;
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new Cell();
cell.CellValue = new CellValue(d.ToString().Replace(",", ".").Replace(" ", ""));
cell.DataType = CellValues.Number;

和幾個(。)更多的品種,以確保 cell.CellValue 包含一個點而不是逗號,但是我的瑞典語 Excel 發瘋了,拒絕將值解釋為小數。 並將其改為 int 。

所以我被困住了。 有沒有人知道如何在 DocumentFormat.OpenXml.Spreadsheet.Cell 中存儲一個十進制值,Excel 將在默認情況下使用逗號作為小數分隔符的系統中正確解釋,無需修復?

還沒有嘗試過,但是類似的東西呢:

var nfi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
...
cell.CellValue = new CellValue(d.ToString(nfi));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM