任务运行两次时,Apache POI将数据附加到xlsx文件 [英] Apache POI appending data to xlsx file when task ran twice

查看:85
本文介绍了任务运行两次时,Apache POI将数据附加到xlsx文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个template.xls文件,我正在从某些数据库查询中添加数据.我添加数据并生成一个名为yyyyMMddHHmmss.xls的新文件.这很好用.文件大小越来越大,因此我试图对xlsx文件执行相同的操作.当我第一次生成文件时,它运行良好.如果我再次运行该过程(即使我重新启动Java应用程序),也将以某种方式将最后一个文件保留在内存中,并将数据追加到该文件中.在这两种情况下,它都是从template.xls(x)提取源文件,这是未修改的文件.

I have a template.xls file that I'm adding data to from some database queries. I add the data and generate a new file named yyyyMMddHHmmss.xls. This works great. The file size is getting large so I'm trying to do the same with an xlsx file. When I generate the file the first time it works great. If I run the process again (even if I restart my java app) it's somehow retaining the last file in memory and appending the data to that file. In both cases it's pulling the source file from template.xls(x) which is an unmodified file.

两者之间的代码是相同的,除了在后一种情况下我传递的是xlsx而不是xls.

The code between the two is identical except I'm passing in xlsx instead of xls in the latter case.

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource("template.xlsx")).getFile());
Workbook workbook = WorkbookFactory.create(file);
// write data
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String currentDate = formatter.format(date);
FileOutputStream fileOutputStream = new FileOutputStream(currentDate + ".xlsx");
workbook.write(fileOutputStream);
fileOutputStream.close();
workbook.close();

我正在使用Java 8u201org.apache.poi:poi:4.1.0(也尝试过4.0.1)

I'm using Java 8u201 and org.apache.poi:poi:4.1.0 (also tried 4.0.1)

推荐答案

As told in Apache POI - FileInputStream works, File object fails (NullPointerException) already, creating a XSSFWorkbook from a File has the disadvantage, that all changes which was made in that workbook always will be stored into that file while XSSFWorkbook.write. This is true even if write writes to another file. But writing explicitly to the same file is not even possible because the File stays open after the workbook was created and so writing into that same file leads to exceptions.

因此使用

Workbook workbook = WorkbookFactory.create(file);

file*.xlsx文件时,

不是一个好主意.相反,需要使用FileInputstream创建Workbook:

is not a good idea when file is a *.xlsx file. Instead the Workbook needs to be created using a FileInputstream:

Workbook workbook = WorkbookFactory.create(new FileInputStream(file));

尽管链接的SO Q/A来自2017年,但使用apache poi 4.1.0始终不会出现相同的问题.

Although the linked SO Q/A is from 2017, the same problem always nor occurs today using apache poi 4.1.0.

这篇关于任务运行两次时,Apache POI将数据附加到xlsx文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆