1. 程式人生 > >使用Jacob自動替換書籤內容

使用Jacob自動替換書籤內容

package ceshi; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class JacobTest { public static void main(String[] args) { //啟動word,生成一個ActivexComponent物件
ActiveXComponent app = new ActiveXComponent("Word.Application"); //要轉換的word檔案 String inFile = "C://Users/Desktop/bookmark.doc"; //要儲存的目標檔案 String tpFile ="C://Users/Desktop/new_bookmark.doc"; boolean flag = true; boolean visible=false; Dispatch docs = app.getProperty("Documents"
).toDispatch(); Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[]{inFile, new Variant(false)}, new int[1]).toDispatch(); //開啟word檔案 , false可寫!! 注意 Variant的值 Dispatch activeDocument=app.getProperty("ActiveDocument").toDispatch(); Dispatch bookMarks = app.call(doc, "Bookmarks"
).toDispatch(); int bCount = Dispatch.get(bookMarks, "Count").getInt(); //獲取書籤數 //將書籤列表存放到list + map 結構中 for (int i = 1; i <= bCount; i++){ Map bookMark = new HashMap(); //建立Map() Dispatch items = Dispatch.call(bookMarks, "Item", i).toDispatch(); String bookMarkKey = String.valueOf(Dispatch.get(items, "Name").getString()).replaceAll("null", ""); //讀取書籤命名 Dispatch range = Dispatch.get(items, "Range").toDispatch(); String bookMarkValue = String.valueOf(Dispatch.get(range, "Text").getString()).replaceAll("null", ""); //讀取書籤文字 String MarkKey=bookMarkKey; String MarkValue=bookMarkValue; //書籤名並替換的內容 if( MarkKey.equals("xm"))//書籤名為xm { MarkValue ="張三"; //該xm書籤處插入張三; } if( MarkKey.equals("lxdh")){//書籤名為lxdh MarkValue ="10086"; //在lxdh書籤處插入10086 } if( MarkKey.equals("****")){ //書籤名自定義 MarkValue ="*****"; //在該書籤插入自定義內容 } Dispatch.put(range, "Text", new Variant(MarkValue)); //通過列印檢視便於debug System.out.println(bookMarkValue); System.out.println(MarkValue); //儲存檔案 Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {tpFile, new Variant(0)} , new int[1]); //new Variant(),這裡面的根據傳入的引數不同,可以另存為不同的型別 } try{ Variant f = new Variant(false); Dispatch.call(doc, "Close", f); flag = true; } catch (Exception e) { e.printStackTrace(); } finally { app.invoke("Quit", new Variant[] {}); } } }