问题
I'm developing an accountancy software, which will also create a report in Excel format (.xls).
I've used NPOI in almost every project that requires an Excel report, without any major problem.
But i'm now facing a problem, and can't seem to find any solution browsing the Internet.
As you can see, midway the report, the Currency column automatically changes format, not formatting properly currency, border, and everything in that column.
I've been working on it for several time, with no success.
Here's the code I've used to create the style (C#):
var baseStyle = workBook.CreateCellStyle();
baseStyle.VerticalAlignment = VerticalAlignment.Top;
baseStyle.FillForegroundColor = IndexedColors.White.Index;
baseStyle.FillPattern = FillPattern.SolidForeground;
baseStyle.BorderTop = BorderStyle.Thin;
baseStyle.BorderBottom = BorderStyle.Thin;
baseStyle.BorderLeft = BorderStyle.Thin;
baseStyle.BorderRight = BorderStyle.Thin;
baseStyle.WrapText = true;
private static void SetCellValuePrice(IRow row, ICellStyle cellStyle, int colIndex, decimal value)
{
var xlCell = row.CreateCell(colIndex);
xlCell.SetCellValue(Convert.ToDouble(value));
var newStyle = row.Sheet.Workbook.CreateCellStyle();
newStyle.CloneStyleFrom(cellStyle);
newStyle.DataFormat = row.Sheet.Workbook.CreateDataFormat().GetFormat("€ #,##0.00");
xlCell.CellStyle = newStyle;
}
And an example of the usage (that seems to give no problems in other cells:
SetCellValue(row, baseStyle, colIndex++, data.Description);
Any guesses? Thanks in advance!
回答1:
The problem is that you're creating a style for each cell, while you should create just ONE style for each type of cell.
var baseStyle = workBook.CreateCellStyle();
...
var priceStyle = workBook.CreateCellStyle();
priceStyle.CloneStyleFrom(numberStyle);
priceStyle.DataFormat = workBook.CreateDataFormat().GetFormat("€ #,##0.00");
private static void SetCellValuePrice(IRow row, ICellStyle cellStyle, int colIndex, decimal value)
{
var xlCell = row.CreateCell(colIndex);
xlCell.SetCellValue(Convert.ToDouble(value));
xlCell.CellStyle = cellStyle;
}
Usage:
SetCellValue(row, priceStyle, colIndex++, data.Description);
来源:https://stackoverflow.com/questions/43662756/formatting-error-in-npoi