方案一、openoffice
这个方案网上很多教程! 在此不写具体的说明,openoffice支持很多文件的转换,简单,易上手,但是大文件转换会存在问题,很慢,容易超时!另外对于excel的预览有问题,比较宽的excel预览的话,会分成多页显示,这样就跟原文件存在较大的差异,于是找到了第二种方案
下面是本篇写的重点方案
方案二、Aspose
这个方案是为了解决宽的excel分页出来的页面有问题,所以我只用了cells,其他类型的文件基本类似,有需求的可以各自尝试,先上步骤:
1.下载包,官网下载的需要破解,否则会有水印
这边提供一个20.7版的包,直接安装到maven即可
链接:https://pan.baidu.com/s/1xZZp9WJm87fEA7vF1Q-dug
提取码:6moz
安装到maven
mvn install:install-file -DgroupId=com.aspose -DartifactId=aspose-cells -Dversion=20.7 -Dpackaging=jar -Dfile=D:\develop\apache-maven-3.8.3\aspose-cells-20.7-crack.jar
引入
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>20.7</version>
</dependency>
使用
public static void main(String[] args) {
excel2pdf("D:\\doc\\test.xlsx", "D:\\doc\\test.pdf");
}
/**
* 生成pdf方法
* @param sPath
* @param dPath
*/
public static void excel2pdf(String sPath, String dPath) {
// 验证License 否则有水印
if (!authrolizeLicense()){
System.out.println("许可证无效!");
}
try {
// 原始excel路径
Workbook wb = new Workbook(sPath);
FileOutputStream fileOS = new FileOutputStream(dPath);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//把内容放在一张PDF 页面上;
pdfSaveOptions.setOnePagePerSheet(true);
//pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
wb.save(fileOS, pdfSaveOptions);
fileOS.flush();
fileOS.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 鉴权
* @return
*/
public static boolean authrolizeLicense() {
boolean result = false;
try {
InputStream is = com.aspose.cells.License.class.getResourceAsStream("/com.aspose.cells.lic_2999.xml");
License asposeLicense = new License();
asposeLicense.setLicense(is);
is.close();
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
直接去目录下查看,发现会生成新的pdf,之前excel问题可解决