java通過jacob調用word
來源:互聯網
上載者:User
word
public static void main(String[] args) { //啟動word,產生一個ActivexComponent對象 ActiveXComponent app = new ActiveXComponent("Word.Application"); //要轉換的word檔案 String inFile = "D:\\project\\java_word\\java_word\\wordtemplet.doc"; //要報存的目標檔案 String tpFile ="D:\\project\\java_word\\java_word\\wordtemplet3.doc"; boolean flag = false; Dispatch xlo = app.getObject(); String oldText="1234"; String newText="test"; boolean visible=false; String bookMarkKey="LB_KJGG"; try { //設定word不可見 app.setProperty("Visible", new Variant(visible)); //log.info("設定word不可見成功!"); System.out.println("設定word不可見成功!"); Dispatch docs = app.getProperty("Documents").toDispatch(); Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method ,new Object[] {inFile, new Variant(false), new Variant(true)} , new int[1]).toDispatch(); //開啟word檔案 //在word2003的vba文檔中application有UserName屬性。 String userName=app.getPropertyAsString("UserName"); System.out.println("使用者名稱:"+userName); Dispatch selection=app.getProperty("Selection").toDispatch(); //得到一個組件 System.out.println("Selection"); Dispatch find = app.call(selection, "Find").toDispatch();
//尋找什麼文本 Dispatch.put(find, "Text", oldText); //替換文本 Dispatch.call(find,"ClearFormatting"); Dispatch.put(find, "Text", oldText); Dispatch.call(find, "Execute"); Dispatch.put(selection, "Text", newText); // Dispatch.call(app, "SaveAs", inFile); System.out.println("replace"); //把指定的值設定到指定的標籤中去 Dispatch activeDocument=app.getProperty("ActiveDocument").toDispatch(); System.out.println("activedocument"); Dispatch bookMarks = app.call(activeDocument, "Bookmarks").toDispatch(); System.out.println("bookmarks"); boolean bookMarkExist1=Dispatch.call(bookMarks,"Exists",bookMarkKey).toBoolean(); if(bookMarkExist1==true){ System.out.println("exists bookmark!"); Dispatch rangeItem = Dispatch.call(bookMarks, "Item",bookMarkKey). toDispatch(); System.out.println("range item!"); Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch(); System.out.println("range !"); //取標籤的值 String bookMarkValue=Dispatch.get(range,"Text").toString(); bookMarkValue="test"; if(bookMarkValue!=null){ Dispatch.put(range, "Text", new Variant(bookMarkValue)); } } else{ System.out.println("not exists bookmark!"); } //儲存檔案 Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {tpFile, new Variant(0)} , new int[1]); //作為word格式儲存到目標檔案 Variant f = new Variant(false); Dispatch.call(doc, "Close", f); flag = true; } catch (Exception e) { e.printStackTrace(); } finally { app.invoke("Quit", new Variant[] {}); }