Java calls word through Jacob
Last Update:2017-02-28
Source: Internet
Author: User
Word
public static void main (string[] args) { //starts Word, generates a Activexcomponent object Activexcomponent app = new Activexcomponent ("Word.Application"); //Word file to convert String inFile = "D:\\project\\java_word\\java_word\\wordtemplet.doc"; //target file to be reported String tpfile = "D:\\project\\java_word\\java_word\\wordtemplet3.doc"; boolean flag = false;& nbsp; Dispatch xlo = App.getobject (); string oldtext= "1234"; string newtext= "Test"; boolean visible=false; String bookmarkkey= "Lb_kjgg"; try { //Set Word not visible app.setproperty (" Visible ", New Variant (Visible)); //log.info (" Set Word not visible success! "); System.out.println ("Set Word not visible success!"); 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 (); Open the Word file //application have username properties in word2003 VBA documents. String username=app.getpropertyasstring ("UserName"); System.out.println ("User name:" +username); Dispatch selection= App.getproperty ("Selection"). Todispatch (); //Get a component System.out.println ("Selection"); Dispatch find = App.call (Selection, "find"). Todispatch ();
//Look up what text dispatch.put (Find, "text", OldText); //Alt text 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"); //Set the specified value to the specified label 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!"); //Tag Value 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!"); } //Save file Dispatch.invoke (Doc, "SaveAs", Dispatch.method, new object[] {tpfile, new Variant (0)} , new int[1]); /Save to target file as Word format Variant f = new Variant (FALSE); Dispatch.call (Doc, "Close", f); flag = true; } catch (Exception e) { e.printstacktrace (); }  finally { app.invoke ("Quit", new variant[] {}); }