Java操作Word——jacob
程序员文章站
2022-06-03 09:05:31
...
- 需要jacob.dll放在windows/system32下,或者放在%JAVA_HOME%/bin下,jacob.jar放在classpath下
-
一个简单的搜索例子:
/** * 获取XXX * @param inFile word文档 * @return */ public static List<String> getNo(String inFile) { List<String> lNo = new ArrayList<String>(); ActiveXComponent wordApp = null; Dispatch docs = null; try { ComThread.InitSTA();// 初始化com的线程 wordApp = new ActiveXComponent("Word.Application"); // 启动word // Set the visible property as required. Dispatch.put(wordApp, "Visible", new Variant(false));// //设置word可见 docs = wordApp.getProperty("Documents").toDispatch();// 所有文档窗口 // inFile = "d://testx.docx"; Dispatch doc = Dispatch.invoke( docs, "Open", Dispatch.Method, new Object[] { inFile, new Variant(false), new Variant(false) },// 参数3,false:可写,true:只读 new int[1]).toDispatch();// 打开文档 Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得word文件的内容 Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs") .toDispatch(); // 所有段落 int paragraphCount = Dispatch.get(paragraphs, "Count").getInt();// 一共的段落数 // System.out.println("paragraphCount:" + paragraphCount); for (int i = 1; i <= paragraphCount; i++) { Dispatch paragraph = Dispatch.call(paragraphs, "Item", new Variant(i)).toDispatch(); Dispatch paragraphRange = Dispatch.get(paragraph, "Range") .toDispatch(); String paragraphContent = Dispatch.get(paragraphRange, "Text") .toString(); if (paragraphContent.contains("abc")) { // System.out.println(paragraphContent.length()); paragraphContent = paragraphContent.replace(" ", ""); // System.out.println("paragraphContent:"+paragraphContent); // System.out.println(paragraphContent.length()); String no = paragraphContent.substring(paragraphContent.indexOf("abc"), paragraphContent.indexOf("abc") + 21); // System.out.println("no:"+no); // System.out.println(no.substring(no.indexOf("abc") + 7)); lNo.add(no.substring(no.indexOf("abc") + 7)); } } } catch(Exception e) { e.printStackTrace(); throw new RuntimeException("发生系统错误!"); } finally { if (docs != null) { Dispatch.call(docs, "Close", new Variant(true)); docs = null; } if (wordApp != null) { Dispatch.call(wordApp, "Quit"); wordApp = null; } ComThread.Release();// 释放com线程 } return lNo; }
- 附件:jacob.dll(x86、x64)、jacob.jar
上一篇: 基于PHP创建Cookie数组的详解
下一篇: 我所分享的技术文章总结(下)——2017
推荐阅读
-
java源代码怎么运行(java源代码运行操作方法)
-
Java办公自动化系统论文(OA办公自动化系统操作)
-
AngularJS操作键值对象类似java的hashmap(填坑小结)
-
Hadoop学习(7)-hive的安装和命令行使用和java操作
-
java在线编辑word插件(Java操作word工具的选择)
-
Java使用Jdbc连接Oracle执行简单查询操作示例
-
AngularJS实现与Java Web服务器交互操作示例【附demo源码下载】
-
java 分布式有哪些技术(java分布式系统操作)
-
WORD中删除指定颜色或者指定字体的内容可批量操作
-
Word的基本功能之批量试操作、灵活式跳转、快捷式移动