【问题标题】:Writing huge excel file(20k records) is taking more then 1 minute java?编写巨大的 excel 文件(20k 记录)需要超过 1 分钟的 java 时间?
【发布时间】:2020-10-30 01:19:45
【问题描述】:

您好,我正在使用 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);
   }

我使用 IOUtils 现在切换到 com.google.common.io.ByteSource

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

【问题讨论】:

  • 这类问题没有完整的例子是无法回答的。见stackoverflow.com/questions/61221133/…。在那里我提供了一个这样的,也告诉了我的结果。
  • Java 管道 I/O(需要额外的线程)将是理想的。但是添加足够大的初始容量也会有所帮助:new ByteArrayOutputStream(10_000_000)openBufferedStream 可能不会改善情况。
  • 如果您有足够的内存,请使用内存流,然后将内存流的内容转储到文件中。我在处理 DB4 文件的库中遇到了这种问题。它避免了连续敲击操作系统执行 IO 操作。

标签: java excel stream apache-poi iostream


【解决方案1】:

Minimal Reproducible Example 将有助于提供更完整的答案。

但是,以下代码使用 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);
  

   }

【讨论】:

  • 它抛出异常说管道已关闭!
  • 如果您可以创建一个最小可重现示例,我可以检查一下。目前,此方法旨在作为一个使用示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多