单元格样式仅在编辑单元格时应用



我正在使用此示例更改文件中特定单元格的颜色

InputStream inp = new FileInputStream("C:\temp\vineet.xlsx");
//InputStream inp = new FileInputStream("workbook.xlsx");

Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();
XSSFCellStyle defaultStyle = (XSSFCellStyle) wb.getCellStyleAt((short) 0);
style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(CellType.STRING);
cell.setCellValue("a test");
if (cell.getCellStyle().equals(defaultStyle)) {
cell.setCellStyle(style);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("C:\temp\vineet.xlsx");
wb.write(fileOut);
fileOut.close();

乍一看没有变化,但是当我尝试使用 excel 编辑单元格值时,单元格变为黄色背景。

您已经获得了所需的行来执行所需的操作,但是您将其注释掉了。

//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

并更改此设置:

style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());

style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());

最新更新