NPOI设置背景颜色不起作用

Sal*_*ony 8 .net c# npoi

我需要设置和删除行的背景颜色.为什么当我将样式设置为行时它不起作用 - 仍然没有行的背景颜色.我试图设置单个单元格的CellStyle属性并使用HSSFStyle.结果是一样的 - 没有背景颜色.这是代码:

        XSSFCellStyle style = (XSSFCellStyle)_myBook.CreateCellStyle();
        // Define cell style according to input color parameter
        XSSFColor colorToFill;
        switch (color)
        {
            default:
                colorToFill = new XSSFColor(Color.Gray);
                break;
        }
        style.SetFillBackgroundColor(colorToFill);
        for (int i = From; i <= To; i++)
        {
            var row = GetCreateRow(i);
            row.RowStyle = style;
        }
Run Code Online (Sandbox Code Playgroud)

PS Document以XSSF格式打开

Gra*_*ank 24

啊,我们每个人都有部分答案!(转换为XSSFCellStyle是我所缺少的,因为ICellStyle没有SetFill方法所以我无法获得自定义颜色,只有一个索引的颜色...)

您需要做两件事:

  1. 调用SetFillForegroundColor,而不是SetFillBackgroundColor.
  2. 设置style.FillPattern = FillPattern.SolidForeground;

显然,填写Excel是双色的,所以当你想要更改填充时,你必须设置一个模式,因为默认是一个没有填充的单元格,这意味着没有FillPattern.SolidForeground是基本填充图案,这意味着您必须设置填充的前景色,而不是填充的背景色.有点反直觉,但"填充"是指"单元格的背景颜色",所以你可以把它想象成"SetBackgroundForegroundColor"/"SetBackgroundBackgroundColor"