首页 文章

如何在创建新的Excel文件时初始化单元格(Apache POI)

提问于
浏览
2

我目前正在使用Apache POI创建空的excel文件(我稍后会阅读和编辑) . 问题是每当我尝试获取单元格时,我总是得到一个空值 . 我已经尝试初始化前几列和行(单元格不再为空)但是使用这种方法,我无法插入新的行和列 . 如何在不设置行数和列数的情况下初始化工作表的所有单元格?谢谢

编辑:嗨这是我创建excel文件的代码 . 我无法使用迭代器来初始化我的所有单元格,因为电子表格没有行和列 .

FileOutputStream fileOut = new FileOutputStream(loc + formID +".xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        for (Row row : sheet) {
            for (Cell cell : row) {
                CellStyle style = workbook.createCellStyle();
                style.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
                cell.setCellValue("");
                cell.setCellStyle(style);
            }
        } 
        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();

1 回答

  • 5

    您可能会发现MissingCellPolicy可以满足您的需求 . 在连续调用getCell时,可以指定MissingCellPolicy,以便在没有单元格时发生某些事情,例如

    Row r = sheet.getRow(2);
    Cell c = r.getCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK);
    c.setCellValue("This will always work, c will never be null");
    

    org.apache.poi.ss.util.CellUtil也可以提供帮助:

    // Get the row, creating it if needed
    Row r = CellUtil.getRow(4, sheet);
    // Get the cell, creating it if needed
    Cell c = CellUtil.getCell(2, r);
    

相关问题