Use Jacob open-source plug-in to operate Microsoft Word

Source: Internet
Author: User
Use Jacob open-source plug-in to operate Microsoft Word Topic

Recently, the project was about to perform document operations. All of them thought of using Java to operate the word and looking for some materials, which were scattered and messy. They asked Google for help this morning, finally, I found an enthusiastic foreign shoe.ArticleI have learned a lot. Therefore, I will translate this article for your reference. This article is very poor in English, but you must hold it in order to learn from shoes.

"Am I the only person on this planet who wants to write MS Word files with Java? "
-Me, after researching Jacob, poi, wordbean and others, all to no informational avail.

"Am I the only one on this planet willing to useJavaOperationMicrosoft WordFile owner??"

-After my researchJacob, poi, wordbeanAnd other open-source plug-ins that do not have good help information for me to use.

Jacob

Jacob is a Java/COM bridge provided by Dan adlerunder a semi GPL license (may not be used in a specified cial product targetted at Java developers, e.g. virtual machines, debuggers. the chance that you are not allowed to use it is very slim ).

Jacob is a Java/COM bridge software under the semi-GPL license constraint. The author is Dan Adler. note: A half GPL license is a commercial software that users are not allowed to apply to Java development, such as virtual machines and debuggers. However, there is a small chance that you are not allowed to use it.

There is no documentation available concerning the practical use of any Microsoft applications; it is, so Adler, intended as a generic Java/COM bridge and not some MS office APIs. however, M. bigatti made a FAQ, which IMHO is not too useful when it comes to MS word; and there is a Jacob mailing list, where I got most of my information, even if it was tedious work.

There is no description of the actual use of Microsoft products. Therefore, the author's idea is to think of it as a general Java/COM bridge component, rather than an API that operates word. However, M. bigatti raised a question. I'm sorry to say that it is too useful for solving word problems. In addition, there is a Jacob mail list where I get most of the information, despite the tedious work order reconciliation.

Now, this isTutorial entirely dedicated to the handling of Microsoft Word with Jacob. If you want Excel stuff, I wowould rather recommend poi, hosted at the Apache Foundation; they have good Excel support, but only word scratchpad stuff. if you just need to insert some unformatted text, an easier solution is the wordbean by Müller & Stein.

Now, this is a guiding material that is fully committed to using Jacob to operate on word. If you want to use Excel, I would rather recommend you use poi, a Project maintained by the Apache Foundation. Poi is well supported by Excel, but lacks word. If you only want to insert text without any format, you can use some simple solutions, such as using wordbean software written by Müller & Stein.

A good alternative to using Jacob may be jawin, which follows exactly the same goal, namely dispatching callto COM objects.

Another alternative to Jacob is jawin, which follows the same objective as Jacob and is also called by calling the COM component.

Author

This document is far from complete; I am always open for suggestions, tips and any enhancements. if you know something, please tell me. the absence of another site like this, in contrast to all the questions on JDC search and Jacob mailing list, imply that my page will be of some usability. my mail Adress isKain at the above domain.

It will take some time to complete this document. I have always adopted comments, suggestions and some improvement methods. If you know something about this, please let me know. After comparing all the problems in JDC search and Jacob's email list, my documents still have certain availability when I like this webpage. In the above domain, my email address is kain.

Update 2006-04: I had a nice email exchange with a guy named Jean Helou; He summarised his experiences with Jacob in a wiki documentation: it contains a section on macros, and is based on MS Word XP. also, he provided me with a link to the useful MS office object model documentation.

Update 2006-04: I had another wonderful email with a guy named Jean Helou. He summed up his experience with Jacob on Wikipedia: is the use of macros Based on the word in the XP system. He also provided me with a connection to the use of Microsoft Object Model documentation.

Update 2006-08: A nice girl named Kathrin eichler emailed me a section on hyperlinks; it is supported ded below. She is using office xp. Thanks Kathrin!

Update 2006-08: A beauty named Kathrin eichler sent me an email about hyperlink usage. She uses the XP office software. Thank you.

Preparations

You need to have two files:Jacob. JarAndJacob. dll. You put the former in your classpath and the latter in c: \ windows \ system32 or your equivalent. I tested jacob both win 98 and Win XP, both with MS Office 97.

Then, I assume you create a new Java class, make a newMain (string [] asargs)Method and are at its beginning.

You need two files:Jacob. JarAndJacob. dll. Put Jacob. jar in the classpath of your project and Put Jacob. dllC: \ windows \ system32 or another directory. I have tested Windows 98 and Windows XP, both of which use office97.

Let's get started.

First, I will create some variables; you can change them almost arbitrarily. They are pretty self explaining.

First, I need to create some variables. You can modify them as needed. Generally, you can see the specific meaning of the variable name.

 
String sdir ="C: \ Java \ Jacob \\";
 
String sinputdoc = sdir +"File_in.doc";
 
String soutputdoc = sdir +"File_out.doc";
 
String soldtext ="[Label: Import: 1]";
 
String snewtext ="I am some horribly long sentence, so long that [insert bullshit here]";
 
BooleanTvisible =True;
 
BooleanTsaveonexit =False;

SoldtextHolds the label that I will search and replace.TvisibleIs only true for debugging purposes, to see whats going on.TsaveonexitIs false since I save explicitly.

SoldtextIndicates the text to be searched and replaced. TvisibleIt is set to true only during debugging, so that you can see the specific operation process. TsaveonexitIt is false until I explicitly Save the operation.

Now, we will open Word and read the document as well as some base variables.

Now, we will open Word and read the document content based on the basic variables defined above.

 
Activexcomponent oword =NewActivexcomponent ("Word. Application");
 
Oword. setproperty ("Visible",NewVariant (tvisible ));
 
Object odocuments = oword. getproperty ("Documents"). Todispatch ();
Object odocument = Dispatch. Call (odocuments ,"Open", Sinputdoc). todispatch ();
 
Object oselection = oword. getproperty ("Selection"). Todispatch ();
 
Object ofind = oword. Call (oselection ,"Find"). Todispatch ();

Run this. It shoshould open Word, but dont do something cool.

Execute the aboveCodeWill open a word, but the above will not be done.

OdocumentsHolds the list of documents.OdocumentHolds our specific documentFile_in.doc.OselectionAndOfindAre objects we need for the next step, selecting and inserting.

OdocumentsSaved the document list (because it is a multi-document application)Program). OdocumentRecognized as the specified file file_in.doc. oselectionAndOfindIs the object for the next operation, mainly used for search and insert operations.

 
Dispatch. Put (ofind ,"Text", Soldtext );
 
Dispatch. Call (ofind ,"Execute");
 
Dispatch. Put (oselection ,"Text", Snewtext );

Now we searchSoldtext, Execute the search (which results in the label being selected inside word), and replace that selection with the new text (which, in turn, is also selected ).

Now we search for soldtext, execute the search statement, and use the new text to replace the selected project.

So next, we leave that select stuff.

So next, let's leave the selected items.

 
Dispatch. Call (oselection ,"Movedown");
Dispatch. Put (oselection ,"Text","\ NSO we got the next line including Br. \ n");

We move the cursor down, into tively leaving the selection (Yes, it works just like a VB macro inside word; works also with moveup, moveleft, moveright). Then, we insert other text.

We move the cursor down to effectively exit the selected project and start inserting other texts. (It works like a VB macro embedded in Word. It has the moveup, moveleft, and moveright functions)

Now we want to format text. Since we always operate with selected text (the whole"Typetext"Directive mentioned at the mailing list didnt quite work for me), we make the format afterwards (unto the selected text, not unto the next-to-be-typed text ).

Now we want to format the text. The method we have been using is to first select the text and then perform the next operation. The following describes how to use it.

 
Object ofont = Dispatch. Get (oselection ,"Font"). Todispatch ();
Dispatch. Put (ofont ,"Bold","1");
 
Dispatch. Put (ofont ,"Italic","1");
 
Dispatch. Put (ofont ,"Underline","0");

Now the selected text ("\ NSO we got... br. \ n") Is both bold and italic.

 
Object oalign = Dispatch. Get (oselection ,"Paragraphformat"). Todispatch ();
 
Dispatch. Put (oalign ,"Alignment","3");

And now the alignment is block (0-left, 1-center, 2-right, 3-block; at least I hope so ;-). for now, this is the minimal thing that can be useful for you. usingMovedownAndTextDirectives you can do the basics.

Now it is in a fast way (0 indicates left alignment, 1 indicates center, 2 indicates right alignment, and 3 indicates fast alignment ). Now this is the least thing you need to do to help you. Use movedown and text to directly do what you want to do.

Save and close

Well, there were a lot of suggestions on the mailing list, but that one worked for me.

There are a lot of suggestions on saving and about in the Jacob mail list, but this is what I use.

 
Object owordbasic = Dispatch. Call (oword ,"Wordbasic"). Getdispatch ();
 
Dispatch. Call (owordbasic ,"Filesaveas", Soutputdoc );

Dont ask me why. It just works.

Don't ask me why, it is indeed valid.

Dispatch. Call (odocument ,"Close",NewVariant (tsaveonexit ));
 
Oword. Invoke ("Quit",NewVariant [0]);

This is straigthforward. No sweat.

Insert Image

Yes its possible to embed images pretty easy.

It is easy to use Jacob to insert images.

 
String simgfile = sdir +"Image.png";
 
Dispatch. Call (oselection ,"Movedown");
 
Object oimage = Dispatch. Get (oselection ,"Inlineshapes"). Todispatch ();
 
Dispatch. Call (oimage ,"Addpicture", Simgfile );

Well, it just works the way shown by the mailing list. Dont ask me about the image format (Text flow and such) though. Better, if you know it, mail me.

Use of hyperlinks

Hyperlinks are also pretty straightforward (courtesy Kathrin eichler, under Office XP ):

Hyperlinks can also be perfectly used directly.

 
String shyperlink ="Http://www.google.com";
 
Dispatch. Put (oselection ,"Text","Text for the link to Google");
 
Object Orange = Dispatch. Call (oselection ,"Range");
 
Object olink = Dispatch. Get (odocument ,"Hyperlinks"). Todispatch ();
 
Dispatch. Call (olink ,"Add", Orange, shyperlink );

I have not tried that personally yet (under office 97), so your mileage may vary.

Table

Holy slimily, I got no idea yet. am researching VB code and stuff. I got some suggestions from the mailing list how to add a row to a table and how to navigate a table, but creating... well, still to come.

So far, there is no good attention. I have studied the VB code and its working principle. I got some suggestions from the mail list, how to add a row and cross a table, but for the Creation operation .... Further research is needed.

LIST/Enumeration

The VB code looks like shit. I have no idea how to work here. still to come.

The VB code looks like a shit. We still need to work hard to achieve the operation without having to do so.

Summary

The above is an article by a foreign friend, which mainly introduces Jacob's usage and hopes to help children's shoes interested in using Java to operate word.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.