Excel Word Pdf 格式转换

发布于:2025-08-30 ⋅ 阅读:(18) ⋅ 点赞:(0)

引入aspose包

手动更新本地mvn仓库

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
       <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文件,引入依赖

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

   /**
     * 许可证字符串
     */
    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);
    }
  /**
     * 直接在内存中将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();
                }
            }
        }
    }
  /**
     * 将 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仓库

     <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 会导致前端异常 

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


    浏览器无法正确识别响应内容类型:第一次设置为 Excel,第二次设置为 PDF,浏览器可能因为前后不一致而报错。
    响应头冲突:部分 Web 容器(如 Tomcat)可能会对重复设置的头部进行处理,但有些前端库或代理服务器(如 Nginx、CDN)可能不接受这种行为,导致连接中断。
    前端报错 network error 或 network not connected:这通常是由于响应头异常导致浏览器或前端请求库(如 axios)无法正常处理响应,从而中断连接。


网站公告

今日签到

点亮在社区的每一天
去签到