前提条件 必须安装 MS office
1.jdk 使用 jdk1.8
2.jacob.dll 放在..\jdk1.8\jre\bin 目录下
3.eclipse 的 jre 版本要和 jdk 一致, window->preferences->java->compiler 勾选 jdk 1.8
4.window->preferences->java->InstalledJREs->Add 配置成 jdk1.8.0_22 版本 然后勾选上 点击 ok,
5. 在项目目录下新建 lib 目录, 将 jacob.jar 文件拷贝到该目录下, 点 build path->configbuild path ->libraries
1)Add JARs-> 选择 lib 目录下的 jacob.jar 点击 Ok
2) 移除项目原来的 JRE System Library ,AddLibrary->JRE System Library 选择之前添加的 jdk1.6.0_22 , 点击 finish
点击 ok,libraries 配置完毕
备注: 3. 出现 Can'tco-create object 问题, 可能是之前调用 dll 后, 没有释放资源, 需要加入如下代码
先导入 importcom.jacob.com.ComThread;// 在 jacob1.9 版本里有这个类, 1.6 和 1.7 版本经测试无法导入此类
- ComThread.InitSTA();// 初始化 COM 线程
- // 以下操作 word 代码
- MSWordManager ms=new MSWordManager(false);
- // 生成一个 MSwordManager 对象, 并且设置显示 Word 程序
- ms.openDocument("D:\\12.doc");
- // 创建一个新的. doc 文件
- ms.putTxtToCell(1, 1, 2, "!!!!");
- // 插入文本
- ms.save("D:\\12.doc");
- // 保存. doc 文件
- ms.close();
- ms.closeDocument();
- // 以上操作 word 代码
- ComThread.Release();// 操作完成后, 释放 COM 线程
4. 以下代码可以避免上述 Can't co-create object 问题
, 在 finally 中释放资源
- ActiveXComponentapp = new ActiveXComponent("Word.Application"); // 启动 word
- StringinFile = "D:\\123.doc"; // 要替换的 word 文件
- try{
- app.setProperty("Visible",new Variant(false)); // 设置 word 不可见
- Dispatchdocs = app.getProperty("Documents").toDispatch();
- Dispatchdoc = Dispatch.invoke(
- docs,
- "Open",
- Dispatch.Method,
- newObject[] { inFile, new Variant(false),
- newVariant(false) }, new int[1]).toDispatch();
- // 打开 word 文件, 注意这里第三个参数要设为 false, 这个参数表示是否以只读方式打开,
- // 因为我们要保存原文件, 所以以可写方式打开.
- Dispatchselection = app.getProperty("Selection").toDispatch();// 获得对 Selection 组件
- Dispatch.call(selection,"HomeKey", new Variant(6));// 移到开头
- Dispatchfind = Dispatch.call(selection, "Find").toDispatch();// 获得 Find 组件
- Dispatch.put(find,"Text", "name"); // 查找字符串 "name"
- Dispatch.call(find,"Execute"); // 执行查询
- Dispatch.put(selection,"Text", "111"); // 替换为 "111"
- Dispatchfind1 = Dispatch.call(selection, "Find").toDispatch();// 获得 Find 组件
- Dispatch.call(selection,"HomeKey", new Variant(6));// 移到开头
- Dispatch.put(find1,"Text", "8 位随机生成密码"); // 查找字符串
- Dispatch.call(find1,"Execute"); // 执行查询
- Dispatch.put(selection,"Text", "222");
- StringnewFileName = "D:\\temp.doc";
- Dispatch.call(doc,"SaveAs", newFileName); // 另存文件
- Dispatch.call(doc,"Close", new Variant(false));
- System.out.println("isover");
- }catch (Exception e) {
- e.printStackTrace();
- }finally {
- app.invoke("Quit",new Variant[] {});
- app.safeRelease();
- }
5.workspace 中的代码要求 D 盘根目录下有 123.doc 文件才能运行, 否则会一致搜索不到相关词汇
工具类:
- package com.guige.base.util;
- import com.jacob.activeX.ActiveXComponent;
- import com.jacob.com.ComFailException;
- import com.jacob.com.ComThread;
- import com.jacob.com.Dispatch;
- import com.jacob.com.Variant;
- import java.util.Date;
- /**
- * TODO
- *
- * @author songaw
- * @date 2018/5/17 9:54
- */
- public class JacobUtil {
- //word 转 PDF
- private static final String wdFormatPDF="17";
- //html 转 xls
- private static final String htmlFormatExcel="51";
- //PPT 转 pdf
- private static final String pptFormatPDF="32";
- //excel 转 PDF
- private static final String xlTypePDF="0";
- /**
- * html 转 excel
- * @param srcFilePath
- * @param targetFilePath
- * @return
- */
- public static boolean htmlToExcel(String srcFilePath, String targetFilePath) {
- ActiveXComponent app = null;
- Dispatch excel = null;
- try {
- app = new ActiveXComponent("Excel.Application");
- System.out.println("***** 正在转换...*****");
- // 设置 Excel 应用程序不可见
- app.setProperty("Visible", false);
- // Workbooks 表示 Excel 程序的所有文档窗口,(
- app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
- Dispatch excels = app.getProperty("Workbooks").toDispatch();
- // 打开要转换的 Excel 文件
- excel = Dispatch.call(excels, "Open", srcFilePath, false,
- true).toDispatch();
- // 设置兼容性检查为 false
- Dispatch.put(excel, "CheckCompatibility", false);
- app.setProperty("DisplayAlerts",false);
- Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[]{targetFilePath, new Variant(htmlFormatExcel)}, new int[1]);
- app.setProperty("DisplayAlerts",true);
- System.out.println("***** 转换成功...*****");
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- if (excel != null) {
- Dispatch.call(excel, "Close", false);
- }
- if (app != null) {
- app.invoke("Quit", new Variant[] {});
- //app.invoke("Quit", 0);
- }
- ComThread.Release();
- }
- }
- /**
- * word 转 pdf
- * @param srcFilePath
- * @param targetFilePath
- * @return
- */
- public static boolean docToPdf(String srcFilePath, String targetFilePath) {
- ActiveXComponent app = null;
- Dispatch doc = null;
- try {
- ComThread.InitSTA();
- app = new ActiveXComponent("Word.Application");
- System.out.println("***** 正在转换...*****");
- app.setProperty("Visible", false);
- Dispatch docs = app.getProperty("Documents").toDispatch();
- doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
- new Object[] { srcFilePath,
- new Variant(false),
- new Variant(true),// 是否只读
- new Variant(false),
- new Variant("pwd") },
- new int[1]).toDispatch();
- //Dispatch.put(doc, "CheckCompatibility", false); // 兼容性检查, 为特定值 false 不正确
- Dispatch.put(doc, "RemovePersonalInformation", false);
- app.setProperty("DisplayAlerts",false);
- Dispatch.call(doc, "ExportAsFixedFormat", targetFilePath, wdFormatPDF); // word 保存为 pdf 格式宏, 值为 17
- app.setProperty("DisplayAlerts",true);
- System.out.println("***** 转换成功...*****");
- return true; // set flag true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- if (doc != null) {
- Dispatch.call(doc, "Close", false);
- }
- if (app != null) {
- app.invoke("Quit", 0);
- }
- ComThread.Release();
- }
- }
- public static boolean pptToPdf(String srcFilePath, String pdfFilePath) {
- ActiveXComponent app = null;
- Dispatch ppt = null;
- try {
- ComThread.InitSTA();
- app = new ActiveXComponent("PowerPoint.Application");
- System.out.println("***** 正在转换...*****");
- Dispatch ppts = app.getProperty("Presentations").toDispatch();
- // 因 POWER.EXE 的发布规则为同步, 所以设置为同步发布
- ppt = Dispatch.call(ppts, "Open", srcFilePath, true,// ReadOnly
- true,// Untitled 指定文件是否有标题
- false// WithWindow 指定文件是否可见
- ).toDispatch();
- //Dispatch.put(ppt, "CheckCompatibility", false); // 兼容性检查, 为特定值 false 不正确
- app.setProperty("DisplayAlerts",false);
- Dispatch.call(ppt, "SaveAs", pdfFilePath, pptFormatPDF); //ppSaveAsPDF 为特定值 32
- app.setProperty("DisplayAlerts",true);
- System.out.println("***** 转换成功...*****");
- return true; // set flag true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- if (ppt != null) {
- Dispatch.call(ppt, "Close");
- }
- if (app != null) {
- app.invoke("Quit");
- }
- ComThread.Release();
- }
- }
- public static boolean excelToPDF(String srcFilePath, String pdfFilePath) {
- ActiveXComponent app = null;
- Dispatch excel = null;
- try {
- ComThread.InitSTA(true);
- app = new ActiveXComponent("Excel.Application");
- System.out.println("***** 正在转换...*****");
- long date = new Date().getTime();
- app.setProperty("Visible", false);
- app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
- Dispatch excels = app.getProperty("Workbooks").toDispatch();
- excel = Dispatch
- .invoke(excels, "Open", Dispatch.Method,
- new Object[] { srcFilePath, new Variant(false), new Variant(false) }, new int[9])
- .toDispatch();
- // 转换格式
- Dispatch.put(excel, "CheckCompatibility", false);
- app.setProperty("DisplayAlerts",false);
- Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] { new Variant(0), // PDF 格式 = 0
- pdfFilePath, new Variant(xlTypePDF) // 0 = 标准 (生成的 PDF 图片不会变模糊) 1 = 最小文件
- // (生成的 PDF 图片糊的一塌糊涂)
- }, new int[1]);
- app.setProperty("DisplayAlerts",true);
- System.out.println("***** 转换成功...*****");
- // 这里放弃使用 SaveAs
- /*
- * Dispatch.invoke(excel,"SaveAs",Dispatch.Method,new Object[]{
- * outFile, new Variant(57), new Variant(false), new Variant(57),
- * new Variant(57), new Variant(false), new Variant(true), new
- * Variant(57), new Variant(true), new Variant(true), new
- * Variant(true) },new int[1]);
- */
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- // TODO: handle exception
- return false;
- }finally {
- if (excel != null) {
- Dispatch.call(excel, "Close", false);
- }
- if (app != null) {
- app.invoke("Quit", new Variant[] {});
- //app.invoke("Quit", 0);
- }
- ComThread.Release();
- }
- }
- }
来源: https://www.cnblogs.com/songanwei/p/9051560.html