NPOI无法更改单元格的字体颜色。

3

我试图按条件更改单元格的字体颜色。这是我的最后一次尝试:

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

然而,当条件满足时,字体并没有改变。似乎样式被应用于循环中获取的所有单元格,而不是特定的单元格。我已经阅读了一些与此问题相关的问题,但是我无法使其正常工作。
这次新的尝试正在格式化所有单元格。无论是否满足条件。
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);
} 

Joao的响应会将所有单元格格式化为“normalStyle”

3个回答

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

(注意:我完全没有测试过这段代码。我忘了CreateCellStyle是否像那样工作。但它至少应该指引你朝正确的方向前进。)

谢谢您的回复!但是它并没有按照预期工作。我已根据您的回答进行了最后一次尝试,并编辑了我的问题。 - Jorge Vazquez
你的编辑肯定行不通。请注意,我的代码在循环之外创建了 ICellStyle 对象,并直接从工作簿中创建它们。你不能只访问 cell.CellStyle 属性并修改其属性,否则你将一直在处理相同的对象。 - João Mendes

2

如果使用XSSF格式,请使用以下方法创建字体并将其分配给单元格

XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
defaultFont.FontName = "Arial";
defaultFont.Color = IndexedColors.Black.Index;
defaultFont.IsBold = false;
defaultFont.IsItalic = false;
defaultFont.Boldweight = 700;

XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle();
defaultStyle.SetFont(defaultFont);

0
所以我最终定义了一个样式,然后将其设置为满足条件的单元格。
IFont redfont = wb.CreateFont();
redfont.Color = IndexedColors.Red.Index;
redfont.FontHeight = 8;
ICellStyle style = wb.CreateCellStyle();

...
if (integrity < 1)
{
    style.CloneStyleFrom(cell.CellStyle);
    style.SetFont(redfont);
    cell.CellStyle = style;
}

感谢您的帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接