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

问题描述 投票:0回答:1

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

    }

}

有什么方法可以为已经存在的单元格提供背景颜色。 (改变单元格样式)

java excel apache-poi
1个回答
0
投票

粘贴来自 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();
© www.soinside.com 2019 - 2024. All rights reserved.