Spring Boot + EasyPOI 实现 Excel 和 Word 导出 PDF 的完整解决方案

Spring Boot + EasyPOI 实现 Excel 和 Word 导出 PDF 的完整解决方案

在企业级开发中,将 Excel 和 Word 文档导出为 PDF 是常见需求(如报表归档、合同存档)。本文将结合 EasyPOI(快速生成 Excel/Word)和 Aspose 系列工具(格式完美转换),详细讲解如何实现 Excel 和 Word 到 PDF 的转换,并解决格式保留、性能优化等核心问题。

1. 环境准备与依赖配置

1.1 依赖配置

pom.xml 中添加以下依赖:

<!-- Spring Boot Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- EasyPOI(Excel/Word 导出) -->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.4.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>4.4.0</version>
</dependency>

<!-- Aspose.Cells(Excel 转 PDF) -->
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-cells</artifactId>
    <version>23.10</version>
</dependency>

<!-- Aspose.Words(Word 转 PDF) -->
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>23.10</version>
</dependency>

1.2 注意事项

  • Aspose 系列工具 是商业库,需购买许可证(试用版有水印)。测试阶段可使用 免费试用版
  • EasyPOI 支持通过注解快速生成 Excel/Word 文件,适用于数据量中等的场景(十万行以内)。

2. Excel 导出并转换为 PDF

2.1 生成 Excel 文件

定义实体类并使用 EasyPOI 注解:

import cn.afterturn.easypoi.excel.annotation.Excel;

@ExcelTarget("User")
public class User {
    @Excel(name = "用户ID", orderNum = "0")
    private Long id;

    @Excel(name = "用户名", orderNum = "1")
    private String username;

    @Excel(name = "密码", orderNum = "2")
    private String password;

    // Getters and Setters
}

使用 ExcelExportUtil 生成 Excel 文件:

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExcelExporter {
    public static void exportExcelToPdf() throws IOException {
        List<User> dataList = new ArrayList<>();
        // 模拟数据
        dataList.add(new User(1L, "Alice", "123456"));
        dataList.add(new User(2L, "Bob", "654321"));

        // 配置导出参数
        ExportParams exportParams = new ExportParams("用户列表", "用户数据");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, dataList);

        // 保存为临时 Excel 文件
        String excelFilePath = "temp.xlsx";
        try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {
            workbook.write(fos);
        }
    }
}

2.2 将 Excel 转换为 PDF

使用 Aspose.Cells 将 Excel 文件转换为 PDF:

import com.aspose.cells.Workbook;
import com.aspose.cells.PdfSaveOptions;

public class ExcelToPdfConverter {
    public static void convertExcelToPdf(String inputPath, String outputPath) throws Exception {
        // 加载 Excel 文件
        Workbook workbook = new Workbook(inputPath);

        // 设置 PDF 保存选项
        PdfSaveOptions options = new PdfSaveOptions();
        options.setOnePagePerSheet(true); // 每个工作表一页

        // 保存为 PDF
        workbook.save(outputPath, options);
    }
}

完整调用示例:

public static void main(String[] args) {
    try {
        String excelFilePath = "temp.xlsx";
        String pdfFilePath = "output.pdf";

        // 生成 Excel 文件
        ExcelExporter.exportExcelToPdf();

        // 转换为 PDF
        ExcelToPdfConverter.convertExcelToPdf(excelFilePath, pdfFilePath);
        System.out.println("Excel 已成功转换为 PDF: " + pdfFilePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3. Word 导出并转换为 PDF

3.1 生成 Word 文件

使用 EasyPOI 生成 .docx 文件(需配置模板):

import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WordExporter {
    public static void exportWordToPdf() throws IOException {
        // 准备数据
        Map<String, Object> map = new HashMap<>();
        map.put("title", "用户信息报告");
        map.put("user", new User(1L, "Alice", "123456"));

        // 加载 Word 模板并填充数据
        XWPFDocument document = WordExportUtil.exportWord07("template.docx", map);

        // 保存为临时 Word 文件
        String wordFilePath = "temp.docx";
        try (FileOutputStream fos = new FileOutputStream(wordFilePath)) {
            document.write(fos);
        }
    }
}

3.2 将 Word 转换为 PDF

使用 Aspose.Words 将 Word 文件转换为 PDF:

import com.aspose.words.Document;
import com.aspose.words.PdfSaveOptions;

public class WordToPdfConverter {
    public static void convertWordToPdf(String inputPath, String outputPath) throws Exception {
        // 加载 Word 文件
        Document doc = new Document(inputPath);

        // 设置 PDF 保存选项
        PdfSaveOptions options = new PdfSaveOptions();
        options.setEmbedFullFonts(true); // 嵌入字体以防止乱码

        // 保存为 PDF
        doc.save(outputPath, options);
    }
}

完整调用示例:

public static void main(String[] args) {
    try {
        String wordFilePath = "temp.docx";
        String pdfFilePath = "output.pdf";

        // 生成 Word 文件
        WordExporter.exportWordToPdf();

        // 转换为 PDF
        WordToPdfConverter.convertWordToPdf(wordFilePath, pdfFilePath);
        System.out.println("Word 已成功转换为 PDF: " + pdfFilePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

4. 注意事项与优化建议

  • 性能优化
  • 大数据量导出时,使用分页或异步处理避免内存溢出。
  • Aspose 系列工具在处理复杂格式时性能优异,但需合理控制并发请求。
  • 格式保留
  • Aspose.Cells/Aspose.Words 能完美保留 Excel/Word 的字体、颜色、合并单元格、图表等格式。
  • Word 转 PDF 时,建议在 PdfSaveOptions 中设置 setEmbedFullFonts(true) 以防止中文乱码。
  • 许可证配置
  • 为 Aspose 系列工具配置正式许可证以去除水印(需将许可证文件放入项目根目录或通过代码加载)。
  • 异常处理
  • 捕获文件读写异常(如 IOException)和转换失败的异常(如 Exception)。
  • 提供友好的错误提示(如“文件格式不支持”或“内存不足”)。

5. 总结

通过 Spring Boot + EasyPOI + Aspose 的组合,开发者可以高效实现 Excel/Word 到 PDF 的转换,满足企业级应用对格式保留和性能的需求。EasyPOI 提供了快速生成文档的能力,而 Aspose 系列工具则确保了转换过程中的格式一致性。尽管 Aspose 是商业库,但其强大的功能和稳定性使其成为企业级项目的首选方案。对于学习成本,建议结合官方文档和示例代码逐步实践,快速掌握核心技术点。

© 版权声明
THE END
喜欢就支持一下吧
点赞14赞赏 分享