如何通过Apache POI在Excel中设置单元格样式?

时间:2017-10-22 07:02:30

标签: java excel apache-poi

我使用Apache POI版本3.9来生成excel,这段代码是正确的:

public CellStyle getCellStyle(XSSFWorkbook workbook){
    CellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("###,###"));
    XSSFFont font = workbook.createFont();
    font.setFontHeightInPoints((short) 11);
    font.setFontName("Tahoma");
    cellStyle.setFont(font);
    CellStyle style = workbook.createCellStyle();
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
    cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    return cellStyle;
}

但升级到3.17时这些行有错误:

style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
    cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);

1 个答案:

答案 0 :(得分:4)

根据版本3.17发行说明here,它说“将单元格对齐常量从CellStyle迁移到Horizo​​ntalAlignment和VerticalAlignment枚举”代替使用代码

style.setVerticalAlignment(VerticalAlignment.TOP);
    cellStyle.setBorderBottom(BorderStyle.THIN);
    cellStyle.setBorderTop(BorderStyle.THIN);
    cellStyle.setBorderRight(BorderStyle.THIN);
    cellStyle.setBorderLeft(BorderStyle.THIN);