You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Aspose将PDF转Excel:如何生成临时文件避免服务器存储

解决方案

直接利用Aspose.PDF的Document.save()方法支持写入OutputStream的特性,用**内存流(ByteArrayOutputStream)**替代物理文件,全程在内存中处理转换后的Excel数据,无需生成持久化文件,之后直接将内存中的字节数据写入数据库即可。

修改后的代码示例:

public void processPdfToExcel(MultipartFile file) throws IOException {
    try (InputStream inputStream = file.getInputStream();
         ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

        Document document = new Document(inputStream);
        ExcelSaveOptions options = new ExcelSaveOptions();
        options.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);

        // 将转换后的Excel数据写入内存流
        document.save(outputStream, options);

        // 将内存流转换为字节数组,用于写入数据库
        byte[] excelBytes = outputStream.toByteArray();

        // 这里执行写入数据库的逻辑,比如存入BLOB字段
        // saveToDatabase(excelBytes);
    }
}

关键说明:

  • 使用ByteArrayOutputStream在内存中暂存转换后的Excel数据,避免磁盘IO操作,也无需创建临时目录或文件。
  • 用try-with-resources语法自动关闭流,避免资源泄漏。
  • 转换完成后通过outputStream.toByteArray()获取Excel文件的字节数组,直接传入数据库操作方法即可,全程无物理文件生成。

内容的提问来源于stack exchange,提问作者Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 17:25:37