如何使用java和Apache POI库覆盖excel文件中的单元格样式?

gojuced7  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(181)

我正在使用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());

    }

}

有没有什么方法可以让我给予背景颜色已经存在的单元格。(改变单元格样式)

ha5z0ras

ha5z0ras1#

从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();

相关问题