Apache POI样式应用于所有单元格

时间:2015-11-11 09:18:37

标签: java excel apache-poi

    Cell cell = row.createCell(1);
    cell.setCellValue(rdf.getEffectiveDate());
    cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));

    cell = row.createCell(2);
    cell.setCellValue(rdf.getExpiryDate());
    cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));

    row.createCell(3).setCellValue(rdf.getPremium());
    row.createCell(4).setCellValue(rdf.getAccountNumber());
    row.createCell(5).setCellValue(rdf.getLedgerName());

我想在上面的两列中应用日期格式。但它正在应用于所有细胞。我该如何防止这种情况。

3 个答案:

答案 0 :(得分:12)

正如文档所述,Cell.getCellStyle()永远不会返回null。

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getCellStyle()

如果没有为Cell显式设置单元格样式,则它将返回默认单元格样式,该样式最初在工作簿中的所有单元格之间共享。然后更改它将明显影响所有没有明确分配样式的单元格。

您需要创建一个新的CellStyle,然后将其分配给相关的单元格。

来自POI开发者指南:

https://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

Workbook wb = new HSSFWorkbook();
    //Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet("new sheet");

    // Create a row and put some cells in it. Rows are 0 based.
    Row row = sheet.createRow(0);

    // Create a cell and put a date value in it.  The first cell is not styled
    // as a date.
    Cell cell = row.createCell(0);
    cell.setCellValue(new Date());

    // we style the second cell as a date (and time).  It is important to
    // create a new cell style from the workbook otherwise you can end up
    // modifying the built in style and effecting not only this cell but other cells.
    CellStyle cellStyle = wb.createCellStyle();
    cellStyle.setDataFormat(
        createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
    cell = row.createCell(1);
    cell.setCellValue(new Date());
    cell.setCellStyle(cellStyle);

    //you can also set date as java.util.Calendar
    cell = row.createCell(2);
    cell.setCellValue(Calendar.getInstance());
    cell.setCellStyle(cellStyle);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();

答案 1 :(得分:3)

尝试创建新的单元格样式。我想你可能正在改变默认风格。所以像这样......

CellStyle dateTimeCS = wb.createCellStyle();
dateTimeCS.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy"));
cell.setCellStyle(dateTimeCS);

答案 2 :(得分:0)

使用RegionUtil将边框应用于一系列单元格

https://poi.apache.org/apidocs/org/apache/poi/ss/util/RegionUtil.html

看起来像是在3.15版本中添加的