NPOI 不会更改单元格的字体颜色

Jor*_*uez 3 c# npoi

我正在尝试有条件地更改单元格的字体颜色。这是我最后一次尝试:

IWorkbook wb = null;

using (FileStream _fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    wb = WorkbookFactory.Create(_fileStream);
    _fileStream.Close();
}



ISheet sheet = wb.GetSheet(sheetName);
IFont font = wb.CreateFont();
...
...

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    ICellStyle redStyle = cell.CellStyle;
    font.Color = IndexedColors.Red.Index;
    redStyle.SetFont(font);
    cell.CellStyle = redStyle;
}
else
{
    ICellStyle normalStyle = cell.CellStyle;
    font.Color = XSSFFont.DEFAULT_FONT_COLOR;
    normalStyle.SetFont(font);
    cell.CellStyle = normalStyle;
}                        
Run Code Online (Sandbox Code Playgroud)

但是,满足条件时字体不会改变。似乎该样式适用于所有单元格,而不是我在循环中进入的单元格。我已经阅读了与此问题相关的一些问题,但我无法使其发挥作用。

这个新尝试是格式化所有单元格。不管是否满足条件

ICellStyle redStyle = cell.CellStyle;
font.Color = IndexedColors.Red.Index;             
redStyle.SetFont(font);    

//This is how I am trying to change cells format 
if (integrity < 1)
{
    cell.CellStyle.SetFont(font);
} 
Run Code Online (Sandbox Code Playgroud)

Joao 响应将使用“normalStyle”格式化所有单元格

Joã*_*des 5

默认情况下,每个单元格将使用相同的 CellStyle 对象。如果您希望不同的单元格具有不同的样式,则必须创建不同的对象。

ICellStyle redStyle = wb.CreateCellStyle();
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

ICellStyle normalStyle = wb.CreateCellStyle();
font.Color = XSSFFont.DEFAULT_FONT_COLOR;
normalStyle.SetFont(font);

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    cell.CellStyle = redStyle;
}
else
{
    cell.CellStyle = normalStyle;
}                        
Run Code Online (Sandbox Code Playgroud)

(注意:我根本没有测试过这段代码。我忘记 CreateCellStyle 是否像那样工作。但它至少应该为您指明正确的方向。)