NPOI 格式错误

Formatting error in NPOI

我正在开发一个会计软件,它还会创建一个 Excel 格式 (.xls) 的报告。
我几乎在每个需要 Excel 报告的项目中都使用了 NPOI,没有出现任何重大问题。

但我现在遇到了一个问题,似乎无法找到任何浏览互联网的解决方案。

如您所见,在报告中途,货币列自动更改格式,货币、边框和该列中的所有内容的格式不正确。

我已经研究了好几次,都没有成功。

这是我用来创建样式的代码 (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;
    }

和一个用法示例(在其他单元格中似乎没有问题:

SetCellValue(row, baseStyle, colIndex++, data.Description);

有什么猜测吗? 提前致谢!

问题是您正在为每个单元格创建一个样式,而您应该为每种类型的单元格只创建一个样式。

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;
}

用法:

SetCellValue(row, priceStyle, colIndex++, data.Description);