欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java操作Word——jacob

程序员文章站 2022-06-03 09:05:31
...
  1. 需要jacob.dll放在windows/system32下,或者放在%JAVA_HOME%/bin下,jacob.jar放在classpath下
  2. 一个简单的搜索例子:
    /**
    	 * 获取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;
    	}
     
  3. 附件:jacob.dll(x86、x64)、jacob.jar
相关标签: jacob