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

如何将org.dhatim.fastexcel.Workbook转为InputStreamSource作为邮件附件?

解决方案

fastexcel的Workbook类确实没有toInputStream()方法,它的核心设计是通过写入OutputStream来生成Excel内容。你可以通过ByteArrayOutputStream中转,再用Spring提供的ByteArrayResource(它是InputStreamSource的实现类)来包装,直接满足邮件附件的需求。

直接看可行的实现代码:

private InputStreamSource getExcelContentAsInputStreamSource(Workbook finalReport) throws IOException {
    // 完成Workbook的写入准备,这一步必须调用
    finalReport.finish();
    
    // 用ByteArrayOutputStream接收Excel内容
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        finalReport.write(baos);
        // 将字节数组包装成ByteArrayResource,它自带InputStreamSource的实现
        return new ByteArrayResource(baos.toByteArray());
    }
}

关键说明

  • 为什么用ByteArrayResource?:它实现了InputStreamSource接口,每次调用getInputStream()都会返回一个新的ByteArrayInputStream,能满足邮件发送时可能多次读取流的需求(避免流被读取一次后就关闭的问题)。
  • 不需要ReadableWorkbook:你之前代码里的ReadableWorkbook是用来读取Excel文件的,这里我们是要生成并输出Excel,完全不需要绕这个弯路。
  • 必须调用finish():fastexcel的Workbook需要先调用finish()来完成文档的收尾工作(比如写入文件尾部标识),否则生成的Excel可能损坏。

把这个方法返回的InputStreamSource直接传给MimeMessageHelper的addAttachment方法即可:

// 示例:添加附件到邮件
mimeMessageHelper.addAttachment("报表.xlsx", getExcelContentAsInputStreamSource(finalReport));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:18:15