前言:
当今数字化时代,电子文档的使用越来越广泛,而Excel和PDF是其中两种常见的文档格式。Excel作为一种强大的电子表格工具,广泛应用于数据分析、报表生成等领域;而PDF作为一种可靠的文档格式,被广泛用于文档的共享和打印。
然而,在某些情况下,我们可能需要将Excel文件转换为PDF格式,以便更好地共享、打印或保护文档内容。在Java技术中,我们可以使用一些开源库来实现Excel到PDF的转换,如Apache POI和iText等。
在本文中,我们将探讨如何使用Java技术将Excel文件转换为PDF格式。
libreoffice下载、安装、启动步骤在专栏【word、excel转pdf】的《基于java技术实现word转pdf》文章中有详细步骤(链接放到文章最后),这里就不在重新写了。因为Aspose.Words是商业版的需要购买证书,原理和word转pdf一样,依赖word换成excel就好,本文提一下libreoffice-excel转pdf
代码:
package com.atxinxin; import com.artofsolving.jodconverter.DocumentConverter; import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter; import java.io.File; /** * @author weixinxin 2024-01-30 **/ public class ExcelToPdf { public static boolean xlsxToPDF(String wordPath, String pdfPath) { try { long startTime = System.currentTimeMillis(); File inputFile = new File(wordPath); File outputFile = new File(pdfPath); OpenOfficeConnection connection = new SocketOpenOfficeConnection("libreoffice安装的服务器ip",1998);//启动命令的指定端口 System.out.println(" 连接到libreoffice==="+ (System.currentTimeMillis() - startTime)); connection.connect(); DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection); converter.convert(inputFile,outputFile); connection.disconnect(); System.out.println("time==" + (System.currentTimeMillis() - startTime)); return true; } catch (Exception ex) { ex.printStackTrace(); } return false; } public static void main(String[] args) throws Exception { String wordPath = "C:\\Users\\weixinxin_ext\\Desktop\\测试excel转pdf.xlsx"; String pdfPath = "C:\\Users\\weixinxin_ext\\Desktop\\测试excel转pdf.pdf"; xlsxToPDF(wordPath, pdfPath); } }
结果:
提一下libreoffice中的converter.convert方法
可以看到这个方法中的参数类型有四种
一、流+文件格式
二、文件+文件格式
三、文件+输出文件+输出文件格式
四、文件
向这种方式,就算不指定格式也会按照文件后缀生成
文章开头提到的文章链接:http://t.csdnimg.cn/gZ9lf