excel转pdf的java实现

一、实现原理

采用java调用vbs脚本调用office应用把excel转成pdf。

支持文件格式:xlsx,xls,csv

二、前期准备

1、安装office软件

2、准备vbs脚本文件,放到C:\excel2pdf_script\目录下。(本文只用2个文件)

三、VBS转换脚本

1、excel_start.vbs

' First, try to get a running instance.
On Error Resume Next
Dim excelApplication
Set excelApplication = GetObject(, "Excel.Application")' If MS Excel is already running, the script is successful.
If Err = 0 ThenWScript.Quit 3
End If
Err.clear' Start MS Excel.
Set excelApplication = CreateObject("Excel.Application")
excelApplication.DisplayAlerts = False
' Add a workbook to keep open, otherwise Excel is shut down implicitly.
excelApplication.Workbooks.Add
If Err <> 0 ThenWScript.Quit -6
End If' Disable execution of macros.
excelApplication.ExcelBasic.DisableAutoMacros' Exit and signal success.
WScript.Quit 3

2、excel_convert.vbs

' See http://msdn.microsoft.com/en-us/library/bb243311%28v=office.12%29.aspx
Const WdExportFormatPDF = 17
Const MagicFormatPDF = 999Dim arguments
Set arguments = WScript.Arguments' Transforms a file using MS Excel into the given format.
Function ConvertFile( inputFile, outputFile, formatEnumeration )Dim fileSystemObjectDim excelApplicationDim excelDocument' Get the running instance of MS Excel. If Excel is not running, exit the conversion.On Error Resume NextSet excelApplication = GetObject(, "Excel.Application")If Err <> 0 ThenWScript.Quit -6End IfOn Error GoTo 0' Find the source file on the file system.Set fileSystemObject = CreateObject("Scripting.FileSystemObject")inputFile = fileSystemObject.GetAbsolutePathName(inputFile)' Convert the source file only if it exists.If fileSystemObject.FileExists(inputFile) Then' Attempt to open the source document.On Error Resume NextSet excelDocument = excelApplication.Workbooks.Open(inputFile, , True)If Err <> 0 ThenWScript.Quit -2End IfOn Error GoTo 0' Convert: See http://msdn2.microsoft.com/en-us/library/bb221597.aspxOn Error Resume NextIf formatEnumeration = MagicFormatPDF ThenexcelDocument.ExportAsFixedFormat xlTypePDF, outputFileElseexcelDocument.SaveAs outputFile, formatEnumerationEnd If' Close the source document.excelDocument.Close FalseIf Err <> 0 ThenWScript.Quit -3End IfOn Error GoTo 0' Signal that the conversion was successful.WScript.Quit 2Else' Files does not exist, could not convertWScript.Quit -4End IfEnd Function' Execute the script.
Call ConvertFile( WScript.Arguments.Unnamed.Item(0), WScript.Arguments.Unnamed.Item(1), CInt(WScript.Arguments.Unnamed.Item(2)) )

3、excel_assert.vbs(这里用不到)

' Configure error handling to jump to next line.
On Error Resume Next' Try to get running MS Excel instance.
Dim excelApplication
Set excelApplication = GetObject(, "Excel.Application")' Signal whether or not such an instance could not be found.
If Err <> 0 thenWScript.Quit -6
ElseWScript.Quit 3
End If

4、excel_shutdown.vbs(如果不需要关闭的话也用不到)

' Try to get currently running instance of MS Excel.
On Error Resume Next
Dim excelApplication
Set excelApplication = GetObject(, "Excel.Application")' If no such instance can be found, MS Excel is already shut down.
If Err <> 0 ThenWScript.Quit 3
End If' Try to shut down MS Excel.
excelApplication.Quit' If this was impossible, exit with an error.
If Err <> 0 ThenWScript.Quit -6
End If
On Error GoTo 0' MS Excel was shut down successfully.
WScript.Quit 3

四、java调用VBS脚本执行转换

ExcelToPdfUtil.java
package com.lan.fts.util;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;/*** Excel转pdf* @author lanhezhong* @date 2021年4月28日*/
public class ExcelToPdfUtil {private Logger log = LoggerFactory.getLogger(getClass());private static String start_script="C:\\excel2pdf_script\\excel_start.vbs";private static String convert_script="C:\\excel2pdf_script\\excel_convert.vbs";
//	private static String shutdown_script="C:\\excel2pdf_script\\excel_shutdown.vbs";private static volatile ExcelToPdfUtil instance=null;private static Runtime cmdRuntime=null;private ExcelToPdfUtil(){}public static ExcelToPdfUtil getInstance(){if(instance==null){synchronized (ExcelToPdfUtil.class) {if(instance==null){instance = new ExcelToPdfUtil();cmdRuntime=Runtime.getRuntime();try {cmdRuntime.exec("wscript "+start_script);} catch (IOException e) {e.printStackTrace();throw new RuntimeException("wscript "+start_script+"fail.", e);}}}}return instance;}public boolean excelToPdf(String fromFilePath, String pdfFilePath){Process process = null;try {File f0 = new File(pdfFilePath);if(f0.exists()){return true;}process = cmdRuntime.exec("wscript "+convert_script+" "+fromFilePath+" "+pdfFilePath+" 999");boolean b = process.waitFor(180, TimeUnit.SECONDS);if(!b){log.error("等待180s仍然转化失败。文件:{}", fromFilePath);return false;}File f = new File(pdfFilePath);if(f.exists() && f.length()>10){return true;}return false;} catch (IOException | InterruptedException e) {log.error("文件转换失败:{}",fromFilePath, e);e.printStackTrace();} finally {try {process.destroyForcibly();process.destroy();}catch (Exception e){log.error("关闭进程失败", e);}}return false;}
}

五、运行测试

    public static void main(String[] args) {ExcelToPdfUtil.getInstance().excelToPdf("D:\\data\\out\\lanhezhong文件转换.xlsx", "D:\\data\\out\\lanhezhong文件转换.xlsx.pdf");}

运行结果:

总结:excel转pdf后,数据格式不是很好,和在excel中是不一样的。office转excel成pdf本身也有这个问题。

***********************************************************************************************
author:蓝何忠
email:lanhezhong@163.com
***********************************************************************************************

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1419979.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

有边数限制的最短路

文章目录 题目 有边数限制的最短路算法分析1、问题&#xff1a;为什么Dijkstra不能使用在含负权的图中&#xff1f;dijkstra详细步骤2、什么是bellman - ford算法&#xff1f;3、bellman - ford算法的具体步骤4、在下面代码中&#xff0c;是否能到达n号点的判断中需要进行if(di…

vue2 八大组件通信,父子通信,跨层级通信,事件总线,vuex等

文章目录 什么是组件通信&#xff1f;父子通信流程propsProps 定义Props 作用特点数组写法对象写法&#xff08;props校验&#xff09;简写只验证数据类型&#xff1a;完整写法&#xff0c;完整的验证&#xff1a; props父向子传值用props父传子在子组件中修改props $emit子向父…

vue3点击添加小狗图片,vue3拆分脚本

我悄悄蒙上你的眼睛 模板和样式 <template><div class"XueXi_Hooks"><img v-for"(dog, index) in dog1List" :src"dog" :key"index" /><button click"addDog1">点我添加狗1</button><hr …

圆柱齿轮的旋向如何判断?

上期出了个题&#xff0c;给了两个内齿轮&#xff0c;请大家来判断他们的旋向&#xff0c;看到了有不少小伙伴评论给出了自己的答案&#xff0c;正确和错误差不多各半吧&#xff0c;错的占比要大一些。这期咱们就好好聊一聊这个问题。 外齿轮的旋向大家貌似判断都没什么问题&a…

Hive行列转换应用与实现

Hive行列转换应用与实现 1.多行转多列 问题引入 解决方法 2.多行转单列 问题引入 解决方法 3.多列转多行 问题引入 解决方法 4.单列转多行

信息系统项目管理师0102:可行性研究的内容(7项目立项管理—7.2项目可行性研究—7.2.1可行性研究的内容)

点击查看专栏目录 文章目录 7.2项目可行性研究7.2.1可行性研究的内容1.技术可行性分析2.经济可行性分析3.社会效益可行性分析4.运行环境可行性分析5.其他方面的可行性分析记忆要点总结7.2项目可行性研究 可行性研究是在项目建议书被批准后,从技术、经济、社会和人员等方面的条…

200+套AxureBi可视化大数据大屏看板原型设计方案

产品名称&#xff1a;200套AxureBi可视化大屏看板原型设计方案 模板数量&#xff1a;200套平均单价0.46元&#xff08;持续增加中~平均每2周一更&#xff09; 软件版本: Axure 8,Axure 9,Axure 10&#xff08;兼容&#xff09; 作品类型: BI数据大屏可视化Axure原型 文件类型: …

多线程-线程安全

目录 线程安全问题 加锁(synchronized) synchronized 使用方法 synchronized的其他使用方法 synchronized 重要特性(可重入的) 死锁的问题 对 2> 提出问题 对 3> 提出问题 解决死锁 对 2> 进行解答 对4> 进行解答 volatile 关键字 wait 和 notify (重要…

SpringBoot中使用MongoDB

目录 搭建实体类 基本的增删改查操作 分页查询 使用MongoTemplate实现复杂的功能 引入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> 在ap…

CentOS 8.5 安装配置 Tinyproxy 轻量代理服务器 Windows10 系统设置http代理 详细教程

1 下载 下载地址 2 上传服务器并解压 tar zxvf tinyproxy-1.11.2.tar.gz 3 安装配置 #安装依赖软件 yum install automake cd tinyproxy-1.11.2/ #生成configure ./autogen.sh # ./configure --prefix/usr/local/tinyproxy make make install 4 配置环境 vim /etc/prof…

【教程】最新MySQL8.3.0社区版安装指南(超详细)

写在前面&#xff1a; 如果文章对你有帮助&#xff0c;记得点赞关注加收藏一波&#xff0c;利于以后需要的时候复习&#xff0c;多谢支持&#xff01; 文章目录 一、下载安装包二、解压安装包三、设置配置文件四、配置系统环境五、初始化操作 此次安装的版本为MySQL社区版&…

【JVM】Class文件的格式

目录 概述 Class文件的格式 概述 Class文件是JVM的输入&#xff0c;Java虚拟机规范中定义了Class文件的结构。Class文件是JVM实现平台无关、技术无关的基础。 1:Class文件是一组以8字节为单位的字节流&#xff0c;各个数据项目按顺序紧凑排列 2:对于占用空间大于8字节的数据…

实验室信息管理系统主要解决哪些问题,能帮实验室从哪些方面提升效率?

实验室信息管理系统&#xff08;LIMS&#xff09;是一种全面精益化管理工具&#xff0c;它对实验室的人、机、料、法、环进行精确管理&#xff0c;使监测业务高效、准确、方便&#xff0c;确保实验室的运行效率和数据安全性得到极大的提升。通过LIMS&#xff0c;实验室能够实现…

Android Studio连接MySQL8.0

【序言】 移动平台这个课程要做一个app的课设&#xff0c;我打算后期增加功能改成毕设&#xff0c;就想要使用MySQL来作为数据库&#xff0c;相对于SQLlite来说&#xff0c;我更熟悉MySQL一点。 【遇到的问题】 一直无法连接上数据库&#xff0c;开始的时候查了很多资料&#…

qt for android 的架构原理

qt for android实现架构&#xff0c;分享这几幅很不错图。来自于 《Qt 林斌&#xff1a;整合Android IVI平台打造统一的Qt数字座舱体验》 1.实现架构图 2.qt for android能力 3.java 和 qt混合开发 4. AutoMotive

微信小程序按钮去除边框线

通常我们去掉按钮边框直接设置 border:0 但是在小程序中无效&#xff0c;设置outline:none也没用&#xff0c;当然可能你会说加权重&#xff1b;试过了无效 实际上该样式是在伪元素::after内&#xff0c;主要你检查css 还看不到有这个关系&#xff0c;鹅厂就是坑多 类样式::…

从loss角度理解LLM涌现能力

如今的很多研究都表明小模型也能出现涌现能力&#xff0c;本文的作者团队通过大量实验发现模型的涌现能力与模型大小、训练计算量无关&#xff0c;只与预训练loss相关。 作者团队惊奇地发现&#xff0c;不管任何下游任务&#xff0c;不管模型大小&#xff0c;模型出现涌现能力…

Axure RP移动端交互元件库/交互原型模板

作品类型&#xff1a;元件库/原型模板 更新日期&#xff1a;2023-12-04 当前版本&#xff1a;V1.3 适用范围&#xff1a;App应用/小程序 Axure版本&#xff1a;Axure 9.0均可打开 文件大小&#xff1a;36.7M 历时两个月制作并整理了手机移动端常用的75种组件、90个常用界面模板…

【算法】最短路问题 bfs 到 dijkstra

1976、到达目的地的方案数 你在一个城市里&#xff0c;城市由 n 个路口组成&#xff0c;路口编号为 0 到 n - 1 &#xff0c;某些路口之间有 双向 道路。输入保证你可以从任意路口出发到达其他任意路口&#xff0c;且任意两个路口之间最多有一条路。 给你一个整数 n 和二维整…

使用socat做端口转发

最近买的云上mongo数据库但是数据库不支持外网访问&#xff0c;准备做iptables转发但是一直不成功&#xff0c;腾讯云官方给予的解释是受服务器内启动的docker影响 做iptables转发会冲突&#xff0c;所以只能另想办法&#xff0c;我发现使用socat做转发也很好用&#xff0c;所以…