我目前正在使用 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();
最佳答案
您可能会发现 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);
关于java - 创建新 Excel 文件时如何初始化单元格 (Apache POI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5466579/