如何在OpenXML中使用格式(#,###。##)为十进制创build一个CellValue

经过几个小时与这个问题斗争,我决定问你是否有人面临这个问题。

我目前正在使用Open XML框架来处理导出Excel文件的需求。 我有的问题是,这个电子表格的其中一列必须是十进制格式(#,###。##),它必须允许总和。 我可以通过使用以下方法完美地以这种格式导出excel:

private static Cell CreateTextCell(string header, UInt32 index, object text, CellStyleIndex cellStyle) { var cell = new Cell { DataType = CellValues.InlineString, CellReference = header + index, StyleIndex = (UInt32)cellStyle }; var istring = new InlineString(); var t = new Text { Text = text.ToString() }; istring.AppendChild(t); cell.AppendChild(istring); return cell; } 

正如你所看到的,我指定了应用我提到的格式的StyleIndex 。 但是这个问题是Excel将这个值识别为一个文本:

在这里输入图像说明

这就是为什么我试图创build一个新的方法,尽快我想在文件中创build一个十进制被调用:

 private static Cell CreateValueCell(string header, UInt32 index, decimal value, CellStyleIndex cellStyle) { var cell = new Cell { DataType = CellValues.Number, CellReference = header + index, StyleIndex = (UInt32)cellStyle, CellValue = new CellValue(value.ToString()) }; return cell; } 

通过这样做,我达到了如何转换为一个数字,但我失去了小数位,你可以看到在下面的图像:

在这里输入图像描述

我看到一个名为DecimalValue的类,但我不知道如何将它附加到单元格。 有关如何解决它的任何想法? 提前致谢。

你应该阅读那篇文章 。

主要的概念是使用带有NumberingFormat自定义CellFormat

  var nformat4Decimal = new NumberingFormat { NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++), FormatCode = StringValue.FromString("#,##0.0000") };