我试图按条件更改单元格的字体颜色。这是我的最后一次尝试:
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”
ICellStyle
对象,并直接从工作簿中创建它们。你不能只访问cell.CellStyle
属性并修改其属性,否则你将一直在处理相同的对象。 - João Mendes