我正在使用 java 和 Apache POI 库对输入 .xlsx 文件进行 Excel 验证。
下面我发布了我的 java 类中的两个函数。当我尝试设置单元格样式时,它没有反映在 Excel 文件中。我在互联网上搜索了相关信息,但他们到处都提供了在创建单元格/行本身时提供样式的代码。
public static CellStyle getNewCellStyle(){
CellStyle style = myWorkBook.createCellStyle();
style.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
style.setFillPattern(CellStyle.ALIGN_FILL);
return style;
}
public static void chCaseNumberColumnValidation(Cell cell){
String cellData = getCellDataValue(cell);
if(cellData.length() == 10){
if(cellData.equals("BLANK") || cellData.trim().length() == 0){
System.out.println("BLANK CELL: " + cell.getRowIndex() + "," + cell.getColumnIndex());
}
if(cellData.charAt(0) != '5'){
System.out.println("DON't START WITH 5: " + cell.getRowIndex() + "," + cell.getColumnIndex());
cell.setCellStyle(getNewCellStyle());
}
}
else{
System.out.println("****INVALID SIZE " + cell.getRowIndex() + "," + cell.getColumnIndex());
}
}
有什么方法可以为已经存在的单元格提供背景颜色。 (改变单元格样式)
粘贴来自 Apache POI 开发人员指南
的设置颜色示例填充和颜色
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short) 1);
// Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(CellStyle.BIG_SPOTS);
Cell cell = row.createCell((short) 1);
cell.setCellValue("X");
cell.setCellStyle(style);
// Orange "foreground", foreground being the fill foreground not the font color.
style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell = row.createCell((short) 2);
cell.setCellValue("X");
cell.setCellStyle(style);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();