如何在 OpenXML 中为格式为 (#,###.##) 的小数创建 CellValue
How to create a CellValue for a Decimal With Format (#,###.##) in 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 将此值识别为文本:
这就是为什么我尝试创建一个新方法,当我想在文件中创建一个小数时立即调用该方法:
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 的 class,但我不知道如何将它附加到单元格。关于如何解决它的任何想法?
你应该阅读 that article。
主要概念是使用自定义 CellFormat
和 NumberingFormat
:
var nformat4Decimal = new NumberingFormat
{
NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++),
FormatCode = StringValue.FromString("#,##0.0000")
};
我目前正在处理使用 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 的 class,但我不知道如何将它附加到单元格。关于如何解决它的任何想法?
你应该阅读 that article。
主要概念是使用自定义 CellFormat
和 NumberingFormat
:
var nformat4Decimal = new NumberingFormat
{
NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++),
FormatCode = StringValue.FromString("#,##0.0000")
};