我目前正在解决使用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 的类,但我不知道如何将其附加到单元格中。关于如何解决它有什么想法吗?
您应该阅读那篇文章。
主要概念是使用自定义
CellFormat
与 NumberingFormat
:
var nformat4Decimal = new NumberingFormat
{
NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++),
FormatCode = StringValue.FromString("#,##0.0000")
};
除了 Layonez 的答案之外,您还必须创建一个 NumberingFormat 到您希望使用的任何小数位格式。例如:
NumberingFormats numberingFormats = new NumberingFormats(
new NumberingFormat { NumberFormatId = 165, FormatCode = "0.0" }, // one decimal place
new NumberingFormat { NumberFormatId = 166, FormatCode = "0.00" }, // two decimal places
new NumberingFormat { NumberFormatId = 167, FormatCode = "0.000" }, // three decimal places
);
之后,您必须为每个 NumberingFormat 创建一个 CellFormat:
CellFormats cellFormats = new CellFormats(
new CellFormat() { NumberFormatId = UInt32Value.FromUInt32(165), ApplyNumberFormat = BooleanValue.FromBoolean(true) }, // index 0: one decimal place
new CellFormat() { NumberFormatId = UInt32Value.FromUInt32(166), ApplyNumberFormat = BooleanValue.FromBoolean(true) }, // index 1: two decimal places
new CellFormat() { NumberFormatId = UInt32Value.FromUInt32(167), ApplyNumberFormat = BooleanValue.FromBoolean(true) }, // index 2: three decimal places
);
使用此功能,您可以创建带有小数值的单元格并指定小数位数:
// one decimal place
new Cell() { CellValue = new CellValue(1.2m), DataType = CellValues.Number, StyleIndex = 0 };
// two decimal place
new Cell() { CellValue = new CellValue(1.25m), DataType = CellValues.Number, StyleIndex = 1 };
// three decimal place
new Cell() { CellValue = new CellValue(1.253m), DataType = CellValues.Number, StyleIndex = 2 };
请记住,您必须在“new CellValue()”中告知值,并将其保留为十进制。如果您更改为其他格式(例如:字符串),您将丢失小数位格式。