Formatting error in NPOI

假如想象 提交于 2019-12-11 03:55:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!