在使用Java apache POI的excel行中填充背景颜色

我正在尝试阅读Excel表格,并使用以下代码填充行的背景颜色:

.... HSSFCellStyle cellStyle1 = workbook.createCellStyle(); cellStyle1.setFillForegroundColor(new HSSFColor.BLACK().getIndex()); cellStyle1.setFillBackgroundColor(new HSSFColor.RED().getIndex()); cellStyle1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); for(int i=0;i < rowCount;i++){ sheet.getRow(i).setRowStyle(cellStyle1); } ... 

当我运行我的代码时,颜色被填满只有空白单元格。 对于包含数据的所有单元,颜色没有变化。 有人可以告诉我为什么这是发生?

事实certificate,设置setFillForegroundColor用于设置单元格背景颜色。 注释掉setFillBackgroundColor,它应该工作。

 CellStyle cellStyle1 = workbook.createCellStyle(); cellStyle1.setFillForegroundColor(IndexedColors.RED.index); //cellStyle1.setFillBackgroundColor(IndexedColors.RED.index); cellStyle1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 

编辑**

工作testing代码

 import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Iterator; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class TestPoi { public static void main(String[] args) throws Exception { System.out.println("Started"); Workbook workbook = new HSSFWorkbook(new FileInputStream("input.xls")); CellStyle cellStyle1 = workbook.createCellStyle(); cellStyle1.setFillForegroundColor(IndexedColors.RED.index); //cellStyle1.setFillBackgroundColor(IndexedColors.RED.index); cellStyle1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); Sheet sheet = workbook.getSheet("Sheet1"); Iterator<Row> rowIterator = sheet.rowIterator(); while(rowIterator.hasNext()){ Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { Cell cell = cellIterator.next(); cell.setCellStyle(cellStyle1); /*HSSFCellStyle style = (HSSFCellStyle)cell.getCellStyle(); style.setFillBackgroundColor(IndexedColors.RED.index);*/ System.out.println(cell.getStringCellValue()); } } workbook.write(new FileOutputStream("output.xls")); System.out.println("Ended"); } } 

简而言之: setRowStyle并没有做你所假设的。

它所做的( 参见源代码 )将样式注册为行默认样式。

  row.setFormatted(true); row.setXFIndex(style.getIndex()); 

它不会遍历一行中的所有单元格并更改其样式。 因此,该样式仅适用于不存在的单元格( 1 )和默认情况下引用行样式的新创build的单元格。

从上面的代码可以看出,样式只是被索引引用。 为了允许行和不同单元格上的不同样式,单元格必须能够引用不同的样式。 单元格样式在逻辑上取代了行样式。 因此,要将样式应用于所有单元格,必须将样式不仅分配给该行,而且也分配给所有现有单元格。

你说在你的问题,你正在阅读文件,然后你尝试着色行。 所以我会假设你自己没有真正创build新的单元格,因为POI应该复制这个行的样式,这可能是一个错误。

你的情况可能是这样(简体):
文档中现有的单元格引用index 0的样式。 您现在创buildindex 1的新样式,并通过setRowStyle将其应用于该行。
所有不存在的( 1 )和新的单元格将使用index 1的样式。 但是现有的单元格仍然指向index 0的样式,因为它们没有自动分配新的样式。

您可能预期setRowStyle的行为与Excel应用程序类似,您可以在其中select整个行并在其上设置样式。 但这不是它的工作原理。 您必须手动迭代并将更改应用于所有单元格。


1 :为了节省空间,仅在逻辑上存在于Excel应用程序中但尚未物理地存在于数据结构中的单元格。 这就是为什么getCell可以返回null ,并且不仅仅是默认返回CELL_TYPE_BLANK的原因。