c# - 如何在 OpenXML 中为格式为 (#,###.##) 的小数创建 CellValue

标签 c# excel openxml

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

enter image description here

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

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;
}

通过这样做,我了解了如何转换为数字,但我丢失了小数位,如下图所示:

enter image description here

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

最佳答案

你应该阅读 that article .

主要概念是使用自定义 CellFormatNumberingFormat:

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

关于c# - 如何在 OpenXML 中为格式为 (#,###.##) 的小数创建 CellValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37399154/

相关文章:

excel - 将日期/时间拆分为 2 列

c# - 使用 OpenXml 创建分页符

c# - ASP.NET MVC 如何获得允许的用户?在 Windows 身份验证中

c# - IsMouseOver 对 DockPanel 中的某些元素返回 false

sql - Access VBA SQL 字符串太长

c# - 在 C# 中将 Excel 范围作为文本数组或单元格格式的快速方法?

sql-server - 为什么 OPENXML 只返回一个元素

openxml - docx 牢不可破的单词

c# - 尝试激活 Controller 类时接口(interface) (IOwnerRepository) 未解析

c# - 覆盖 Dictionary.Add