【问题标题】:How to create a CellValue for a Decimal With Format (#,###.##) in OpenXML如何在 OpenXML 中为带格式 (#,###.##) 的小数创建 CellValue
【发布时间】:2018-02-21 07:16:31
【问题描述】:

我目前正在处理使用 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 将此值识别为文本:

这就是为什么我尝试创建一个新方法,当我想在文件中创建一个小数时立即调用它:

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 的类,但我不知道如何将它附加到单元格中。关于如何解决它的任何想法?

【问题讨论】:

    标签: c# excel openxml


    【解决方案1】:

    您应该阅读that article

    主要概念是使用自定义CellFormatNumberingFormat

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

    【讨论】:

      猜你喜欢
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      相关资源
      最近更新 更多