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.hqwc.cn/news/687693.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【机器学习300问】85、Adam梯度下降优化算法的原理是什么?

Adam优化算法取了两个算法名称的首字母——Adaptive Moment Estimation的缩写&#xff0c;结合了Momentum算法和RMSprop算法的优点。在Momentum中&#xff0c;会计算前一时刻的梯度&#xff0c;并将其用于当前时刻的梯度更新&#xff1b;而RMSprop会对梯度的大小进行自适应调整…

提高Rust安装与更新的速度

一、背景 因为rust安装过程中&#xff0c;默认的下载服务器为crates.io&#xff0c;这是一个国外的服务器&#xff0c;国内用户使用时&#xff0c;下载与更新的速度非常慢&#xff0c;因此&#xff0c;我们需要使用一个国内的服务器来提高下载与更新的速度。 本文推荐使用字节…

在windows下安装wsl子系统

一、安装环境 windows规格 版本Windows 10企业版版本号22H2操作系统内部版本19045.4291 二、安装过程 2.1 以管理员身份打开PowerShell&#xff08;win X快捷键&#xff09;&#xff1b; 2.2 输入命令&#xff1a;wsl --list --online&#xff08;简写&#xff1a;wsl -l …

FreeRTOS学习 -- 列表和列表项

列表和列表项是 FreeRTOS 的一个数据结构&#xff0c;FreeRTOS 大量使用到了列表和列表项。 一、什么是列表和列表项 1、列表 列表是 FreeRTOS 中的一个数据结构&#xff0c;被用来跟踪 FreeRTOS 中的任务。与列表相关的全部东西都在文件 list.c 和 list.h中。 List_t 结构体…

手写一个SPI FLASH 读写擦除控制器(未完)

文章目录 flash读写数据的特点1. 扇擦除SE&#xff08;Sector Erase&#xff09;1.1 flash_se 模块设计1.1.1 信号连接示意图&#xff1a;1.1.2 SE状态机1.1.3 波形图设计&#xff1a;1.1.4 代码 2. 页写PP(Page Program)2.1 flash_pp模块设计2.1.1 信号连接示意图&#xff1a;…

Python注意事项【自我维护版】

各位大佬好 &#xff0c;这里是阿川的博客 &#xff0c; 祝您变得更强 个人主页&#xff1a;在线OJ的阿川 大佬的支持和鼓励&#xff0c;将是我成长路上最大的动力 阿川水平有限&#xff0c;如有错误&#xff0c;欢迎大佬指正 本篇博客在之前的博客上进行的维护 创建Python…

服务器内存占用不足会怎么样,解决方案

在当今数据驱动的时代&#xff0c;服务器对于我们的工作和生活起着举足轻重的作用。而在众多影响服务器性能的关键因素当中&#xff0c;内存扮演着极其重要的角色。 服务器内存&#xff0c;也称RAM&#xff08;Random Access Memory&#xff09;&#xff0c;是服务器核心硬件部…

AC/DC电源模块的节能技术与环保优势

BOSHIDA AC/DC电源模块的节能技术与环保优势 AC/DC电源模块是一种广泛应用于各种电子设备中的电源转换器。随着环保意识的增强&#xff0c;节能技术成为了设计和生产这些模块的关键考虑因素。本文将介绍AC/DC电源模块的节能技术以及它们所带来的环保优势。 首先&#xff0c;AC…

Ps 滤镜:深色线条

Ps菜单&#xff1a;滤镜/滤镜库/画笔描边/深色线条 Filter Gallery/Brush Strokes/Dark Strokes 深色线条 Dark Strokes滤镜通过以独特的线条风格重绘图像的暗部和亮部来增强图像的视觉效果&#xff0c;适用于创作具有强烈对比和动态线条效果的艺术作品。 “深色线条”滤镜可以…

MySQL企业级开发重点之事物和索引

事物 -- 解散学工部 delete from tb_dept where id 1;-- 删除部门下的员工 delete from tb_emp where dept_id 1; 介绍和操作 我们应该将两个语句写成一个语句 -- 开启事物 start transaction ;-- 解散学工部 delete from tb_dept where id 3;-- 删除部门下的员工 delete fr…

Java设计模式 _行为型模式_解释器模式

一、解释器模式 1、解释器模式 解释器模式&#xff08;Interpreter Pattern&#xff09;是一种行为型模式。它提供了评估语言的语法或表达式的方式。通过实现了一个表达式接口&#xff0c;通常该接口解释一个特定且重复出现的问题。 2、实现思路 &#xff08;1&#xff09;、…

担心源代码泄露?五种有效的方式做到源代码加密防泄露!

对于软件开发公司来说&#xff0c;源代码是企业的核心财产&#xff0c;其安全性不容忽视。源代码泄露不仅可能导致技术秘密被窃取&#xff0c;还可能给企业带来法律纠纷和经济损失。因此&#xff0c;保护源代码的安全至关重要。本文将介绍五种有效的方式进行源代码保护&#xf…