首页 文章

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

提问于
浏览
0

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

    }

}

有什么方法可以为已经存在的细胞提供背景颜色 . (改变细胞样式)

1 回答

  • 0

    粘贴Apache POI Developer Guide设置颜色的示例

    Fills and colors

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

相关问题