繁体   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