编写巨大的excel文件(2万条记录)需要1分钟以上的时间java



嗨,我使用的是apache POI,为了写入工作簿,我使用SXSSFWorkbook,因为数据将是巨大的,

每件事看起来都很好,但在将工作簿转换为输入流时,导出报告需要花费大量时间。

这是我的代码

public StreamedContent generateStreamRep(String fileName, Workbook wb) {
try (ByteArrayOutputStream dsf = new ByteArrayOutputStream();){     
wb.write(dsf);      
file = new DefaultStreamedContent(ByteSource.wrap(dsf.toByteArray()).openStream(), "xlsx", fileName);
}

我用的是欠条,现在换成了com.google.common.io.ByteSource

查看了PipedStream,但没有获得适当的资源。

一个最小可复制示例将有助于提供更完整的答案。

但是,下面的代码使用PipedStreams来加速问题代码中显示的操作。然而,您从这种方法中获得的好处不能超过2个并行进程中最快的一个。或者,换句话说,最后的持续时间不能比并行操作中较慢的持续时间快。在PipedStreams方法中,您需要2个Streams。将写入数据的PipedOutputStream和将消耗数据的PipedInputStream。要从这种方法中获益,您需要并行运行这两个操作。

public StreamedContent generateStreamRep(final String fileName, final Workbook wb) {
try (final PipedOutputStream dsf = new PipedOutputStream ();
final PipedInputStream sink=new PipedInputStream (dsf);){     
final ExecutorService executorService= Executors.newSingleThreadExecutor();
//Write to output stream
executorService.execute(()->wb.write(dsf));
//read from input stream
file = new DefaultStreamedContent(sink, "xlsx", fileName);
executorService.shutdown();
//wait until task is finished or until a maximum time, which ever comes first. Normally in this case the task is already finished
executorService.awaitTermination(2,TimeUnit.Minutes);

}

最新更新