Excel Word Pdf 格式转换

引入aspose包

手动更新本地mvn仓库

java 复制代码
mvn install:install-file -Dfile=C:\aspose-cells-22.9.jar -DgroupId=aspose -DartifactId=aspose-cells -Dversion=22.9 -Dpackaging=jar
mvn install:install-file -Dfile=C:\aspose-pdf-22.9.jar -DgroupId=aspose -DartifactId=aspose-pdf -Dversion=22.9 -Dpackaging=jar
java 复制代码
       <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>22.9</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-pdf</artifactId>
            <version>22.9</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>23.1</version>
        </dependency>

配置pom文件,引入依赖

设置许可证,简单实现转换方法:

java 复制代码
   /**
     * 许可证字符串
     */
    private static final String LICENSE = "<License>" +
            "<Data>" +
            "<Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products>" +
            "<EditionType>Enterprise</EditionType>" +
            "<SubscriptionExpiry>20991231</SubscriptionExpiry>" +
            "<LicenseExpiry>20991231</LicenseExpiry>" +
            "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>" +
            "</Data>" +
            "<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>" +
            "</License>";


    /**
     * 设置 license 去除水印
     */
    private static void setLicense() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(LICENSE.getBytes());
        License license = new License();
        license.setLicense(byteArrayInputStream);
    }
java 复制代码
  /**
     * 直接在内存中将Excel字节数组转换为PDF字节数组
     *
     * @param excelBytes excelBytes
     * @return byte[]
     * @throws Exception
     */
    public static byte[] convertExcelToPdf(byte[] excelBytes) throws Exception {
        // 确保已设置Aspose许可证
        setLicense();

        try (InputStream is = new ByteArrayInputStream(excelBytes);
             ByteArrayOutputStream pdfOut = new ByteArrayOutputStream()) {

            // 手动创建和管理 Aspose Workbook
            Workbook workbook = null;
            try {
                workbook = new Workbook(is);

                PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
                pdfSaveOptions.setOnePagePerSheet(true);

                for (int i = 0; i < workbook.getWorksheets().getCount(); i++) {
                    workbook.getWorksheets().get(i).setVisible(true);
                }

                workbook.save(pdfOut, pdfSaveOptions);
                return pdfOut.toByteArray();
            } finally {
                // 手动释放 Aspose Workbook 资源
                if (workbook != null) {
                    workbook.dispose();
                }
            }
        }
    }
java 复制代码
  /**
     * 将 Excel 文件转换为 Word 文档(通过PDF中间格式)
     *
     * @param excelBytes Excel文件的字节数组
     * @return 生成的Word文档字节数组
     * @throws Exception 转换过程中可能抛出的异常
     */
    public static byte[] convertExcelToWordViaPdf(byte[] excelBytes) throws Exception {
        // 确保已设置Aspose许可证
        setLicense();
        setLicensePdf();

        Workbook workbook = null;

        try {
            // 第一步:Excel 转 PDF
            byte[] pdfBytes;
            try (InputStream is = new ByteArrayInputStream(excelBytes);
                 ByteArrayOutputStream pdfOut = new ByteArrayOutputStream()) {

                workbook = new Workbook(is);

                // 设置PDF保存选项
                PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
                // 不强制每页一个工作表
                pdfSaveOptions.setOnePagePerSheet(false);
                // 所有列显示在一页上
                pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);

                // 保存为PDF格式
                workbook.save(pdfOut, pdfSaveOptions);
                pdfBytes = pdfOut.toByteArray();
            } finally {
                if (workbook != null) {
                    workbook.dispose();
                }
            }
            log.info("Excel 转 PDF 成功");

            // 第二步:PDF 转 Word(使用aspose-words处理PDF)
            byte[] wordBytes;
            try (InputStream pdfInputStream = new ByteArrayInputStream(pdfBytes);
                 ByteArrayOutputStream wordOut = new ByteArrayOutputStream()) {

                // 使用Aspose.PDF加载PDF并转换为Word
                com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document(pdfInputStream);
                // 保存为Word格式
                pdfDocument.save(wordOut, com.aspose.pdf.SaveFormat.DocX);
                wordBytes = wordOut.toByteArray();

                // 释放资源
                pdfDocument.dispose();
            }
            log.info("Excel 转 PDF 转 Word 成功");

            return wordBytes;
        } catch (Exception e) {
            throw new Exception("Excel转Word失败: " + e.getMessage(), e);
        }
    }

    /**
     * 将Excel字节数组转换为Word文档字节数组
     *
     * @param excelBytes Excel文件的字节数组
     * @return Word文档的字节数组
     * @throws Exception 转换过程中可能抛出的异常
     */
    public static byte[] excelToWord(byte[] excelBytes) throws Exception {
        // 确保已设置Aspose许可证
        setLicense();
        // 从字节数组加载Excel工作簿
        Workbook workbook = new Workbook(new ByteArrayInputStream(excelBytes));

        // 创建DOCX保存选项
        DocxSaveOptions options = new DocxSaveOptions();
        options.setClearData(true);
        options.setCreateDirectory(true);
        options.setMergeAreas(true);

        // 将Excel保存为Word字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.save(outputStream, options);

        return outputStream.toByteArray();
    }

修改依赖groupId,不再需要手动更新本地mvn仓库

java 复制代码
     <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>23.1</version>
        </dependency>
        <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-pdf</artifactId>
            <version>22.9</version>
        </dependency>
        <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-words</artifactId>
            <version>23.1</version>
        </dependency>

其他问题:ContentType

不能重复设置response.setContentType 会导致前端异常

java 复制代码
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        if ("pdf".equals(type)) {
            response.setContentType("application/pdf");
        }

浏览器无法正确识别响应内容类型:第一次设置为 Exce l,第二次设置为 PDF ,浏览器可能因为前后不一致而报错。

响应头冲突:部分 Web 容器(如 Tomcat)可能会对重复设置的头部进行处理,但有些前端库或代理服务器(如 Nginx、CDN)可能不接受这种行为,导致连接中断。

前端报错 network error 或 network not connected:这通常是由于响应头异常导致浏览器或前端请求库(如 axios)无法正常处理响应,从而中断连接。

相关推荐
优化控制仿真模型4 小时前
【2026年最新】英语四级历年真题及答案解析PDF电子版(2015-2025年12月)
经验分享·pdf
luyun0202024 小时前
Word题库转换,吾爱出品
windows·word·figma
热爱生活的五柒4 小时前
如何将word中latex公式复制到另一个文档中
word·latex
asdzx674 小时前
使用 Python 快速为 PDF 添加背景色或背景图片
python·pdf
fanchenxinok5 小时前
LIN矩阵Excel ⇄ LDF互转工具:打通设计数据与协议描述的关键桥梁
矩阵·excel·lin·ldf·excel和ldf互转
拆房老料7 小时前
多人协同编辑Excel时,筛选相互干扰怎么办?Onlyoffice中国版给出了与WPS一样的答案
编辑器·excel·开源软件·wps
Data-Miner7 小时前
Excel-Agent:你的专属 AI 数据分析助手
人工智能·数据分析·excel
其实秋天的枫7 小时前
【26年3月最新】计算机二级WPS真题试题及答案14套电子版PDF(含操作题和选择题)
经验分享·pdf
DeskUI~~7 小时前
倚天剑术34--批量获取PDF文档中的图片
pdf
河北之花7 小时前
演示软件界面及快捷键、幻灯片操作、输出为PDF
pdf·wps