I'm trying to format decimal and integer numbers like "1,000.00" in my .xlsx file.
The code for generating stylesheet:
private Stylesheet GenerateStylesheet()
{
//styling and formatting
var cellFormats = new CellFormats();
uint iExcelIndex = 164;
//number formats
var numericFormats = new NumberingFormats();
var nformat4Decimal = new NumberingFormat
{
NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++),
FormatCode = StringValue.FromString("#,##0.00")
};
numericFormats.Append(nformat4Decimal);
//cell formats
var cellFormat = new CellFormat
{
NumberFormatId = nformat4Decimal.NumberFormatId,
FontId = 0,
FillId = 0,
BorderId = 0,
FormatId = 0,
ApplyNumberFormat = BooleanValue.FromBoolean(true)
};
cellFormats.Append(cellFormat);
numericFormats.Count = UInt32Value.FromUInt32((uint)numericFormats.ChildElements.Count);
cellFormats.Count = UInt32Value.FromUInt32((uint)cellFormats.ChildElements.Count);
var stylesheet = new Stylesheet();
stylesheet.Append(numericFormats);
return stylesheet;
}
The code for adding stylesheet to the document:
WorkbookStylesPart stylesPart = workbookpart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = GenerateStylesheet();
stylesPart.Stylesheet.Save();
And this is how cell is generated:
var numberCell = new Cell
{
DataType = CellValues.Number,
CellReference = header + index,
CellValue = new CellValue(text),
StyleIndex = 0
};
Via OpenXML productivity tool I can see that number style is there and it's "applied" to the cell.
But when opening generated document value in the cell is not formatted as expected.
Also, I've discovered that #,##0.00
is one of the default Excel formats with ID = 4. But changing NumberFormatId = nformat4Decimal.NumberFormatId
to NumberFormatId = 4
has no affect.