Java calls Word through Jacob

xiaoxiao2021-03-06  14

The principle of JCOB is to operate the ActiveX object of Word through an interface. The current version is 1.9. First: Copy JCOB.dll to the System32 directory. Second: Place the path of jcob.jar in the classpath directory. Finally: Write access classes.

Public static void main (String [] args) {// Start Word, generate an ActiveXComponent App = New ActiveXComponent ("Word.Application"); // To convert Word file string infile = "d: // suppli /java_word//java_word//wordTemplet.doc "; // The target file to be reported 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 {// Setting Word Not visible App.SetProperty ("Visible", New Variant (Visible); //log.info ("Set Word Inaso!"); System.out.println ("Setting Word Not Obtain!"); 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 // VBA text in Word2003 The Application has a username property in the file. String username = app.getPropertysstring ("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 ();

// What text Dispatch.put (Find, "Text", OldText); // Replace 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"); // Specify is set to the value specified tags to 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 ") .to Dispatch (); system.out.println ("Range!"); // Take the value of the label 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"

转载请注明原文地址:https://www.9cbs.com/read-48393.html

New Post(0)