使用 Apache POI 创建新的 sheet 会删除所有现有的 sheet
Creating new sheet using Apache POI removes all the existing sheets
我尝试使用 Apache poi 库将新 sheet 添加到现有 excel 文件,如下面的代码所示。
FileOutputStream fileOut = new FileOutputStream(new File(BASE_PATH+outputFile));
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Splitted Rules");
Set<String> tags = outputRules.keySet();
int i = 0;
for (String tag : tags) {
List<String> rules = outputRules.get(tag);
for (String rule : rules) {
Row row = sheet.createRow(i++);
row.createCell(0).setCellValue(tag);
row.createCell(1).setCellValue(rule);
}
}
wb.write(fileOut);
fileOut.close();
wb.close();`
问题是文件中的所有 sheet 都被删除了,只有新的 sheet 存在。
这是什么问题?
评论已经暗示了解决方案。
以上代码创建一个新工作簿并覆盖任何现有文件。
如果要将 sheet 附加到现有工作簿,请使用 WorkbookFactory.create 方法(或具有适当参数的 XSSFWorkbook 构造函数)根据现有 excel 文件。
我尝试使用 Apache poi 库将新 sheet 添加到现有 excel 文件,如下面的代码所示。
FileOutputStream fileOut = new FileOutputStream(new File(BASE_PATH+outputFile));
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Splitted Rules");
Set<String> tags = outputRules.keySet();
int i = 0;
for (String tag : tags) {
List<String> rules = outputRules.get(tag);
for (String rule : rules) {
Row row = sheet.createRow(i++);
row.createCell(0).setCellValue(tag);
row.createCell(1).setCellValue(rule);
}
}
wb.write(fileOut);
fileOut.close();
wb.close();`
问题是文件中的所有 sheet 都被删除了,只有新的 sheet 存在。
这是什么问题?
评论已经暗示了解决方案。
以上代码创建一个新工作簿并覆盖任何现有文件。
如果要将 sheet 附加到现有工作簿,请使用 WorkbookFactory.create 方法(或具有适当参数的 XSSFWorkbook 构造函数)根据现有 excel 文件。