Jacob開(kāi)源插件操作Microsoft Word
使用Jacob開(kāi)源插件操作Microsoft Word
主題
最近項(xiàng)目中要進(jìn)行公文的操作,所有就想到了使用Java來(lái)操作word,找了一些資料,都是比較零散、雜亂的東西,今早向Google大神求救,終于發(fā)現(xiàn)了一位熱心的國(guó)外同學(xué)的文章,收獲頗多,因此將此文翻譯出來(lái),供大家參考,本文英語(yǔ)水平很爛,但是為了學(xué)習(xí)同鞋你一定要hold住。
"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.
“難道我是這個(gè)星球上唯一的一個(gè)愿意使用Java操作Microsoft Word文件的人嗎?”
-我在研究Jacob,POI,WordBean和其他開(kāi)源插件后發(fā)現(xiàn)沒(méi)有好的幫助信息可以供我使用。
Jacob介紹
Jacob is a Java/COM bridge provided by Dan Adlerunder a semi GPL license (may not be used in a commercial product targetted at java developers, e.g. virtual machines, debuggers. The chance that you are not allowed to use it is very slim).
Jacob是在半GPL許可證約束下的java/COM橋接軟件,作者是Dan Adler.注:半GPL許可證是使用者不允許將軟件應(yīng)用于java開(kāi)發(fā)的商業(yè)化軟件中,比如虛擬機(jī)、調(diào)試器等。但是你不被允許使用的機(jī)會(huì)是很小的。
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 API. 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.
這里沒(méi)有任何關(guān)于微軟產(chǎn)品的實(shí)際使用的說(shuō)明;因此,作者的想法是想它作為一個(gè)通用的java/COM橋組件,而不是作為一個(gè)操作word的API。然而,M. Bigatti提出了一個(gè)問(wèn)題,恕我直言它對(duì)于解決word的問(wèn)題是不是太有用了;并且有一個(gè)Jacob郵件列表,在哪里我得到了大部分的信息,盡管這個(gè)工作單調(diào)和乏味。
Now, this is a tutorial entirely dedicated to the handling of Microsoft Word with Jacob. If you want Excel stuff, I would rather recommend POI, hosted at the Apache Foundationthey 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 Mller&Stein.
現(xiàn)在,這是一個(gè)完全致力于使用Jacob對(duì)Word進(jìn)行操作的指導(dǎo)材料。如果你希望使用Excel,那么我寧愿推薦你使用POI,由阿帕奇基金會(huì)維護(hù)的項(xiàng)目;POI由對(duì)Excel由很好的支持,但是在Word方面還有點(diǎn)欠缺。如果你只想插入一些沒(méi)有格式的文字,那么可以使用一些簡(jiǎn)單點(diǎn)的解決方案,比如使用Mller&Stein編寫(xiě)的WordBean軟件。
A good alternative to using Jacobmay be Jawin, which follows exactly the same goal, namely dispatching calls to COM objects.
還有一個(gè)Jacob的替代品是Jawin,這個(gè)遵循著與Jacob一樣的目標(biāo),也是通過(guò)調(diào)用COM組件的方式調(diào)用的。
作者
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 is kain at the above domain.
這篇文檔要完成還要花費(fèi)一段時(shí)間;我一直是采納大家的意見(jiàn)、建議和一些改進(jìn)方法。如果你知道關(guān)于這個(gè)方面的東西,請(qǐng)告訴我。在對(duì)比了JDC搜索和Jacob郵件列表里面的所有問(wèn)題后,在喜歡這個(gè)網(wǎng)頁(yè)的情況下我的文檔還是有一定的可用性的。在上述域中我的郵箱地址是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:我與一個(gè)叫Jean Helou的家伙又一段精彩的郵件交流;他在維基百科上面總結(jié)了他對(duì)Jacob的使用經(jīng)驗(yàn):是在基于XP系統(tǒng)中的Word關(guān)于宏的使用。他還提供給我一個(gè)關(guān)于微軟對(duì)象模型文檔的使用連接。
Update 2006-08: A nice girl named Kathrin Eichler emailed me a section on hyperlinks; it is included below. She is using Office XP. Thanks Kathrin!
Update 2006-08:一位叫Kathrin Eichler的美女發(fā)給我了一份關(guān)于超鏈接使用的郵件;在下面有介紹。她使用的是xp版的office軟件,感謝她。
準(zhǔn)備工作
You need to have two files: jacob.jarand jacob.dll. You put the former in your classpath and the latter in c:windowssystem32 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 new main(String[] asArgs)method and are at its beginning.
你需要由兩個(gè)文件:jacob.jar和 jacob.dll。需要把jacob.jar放到你工程的classpath中并且把jacob.dll放到c:windowssystem32目錄下或者其他相應(yīng)的目錄下。我在win98和win xp下面做過(guò)測(cè)試,兩者都是使用的office97。
讓我們開(kāi)始吧
First, I will create some variables; you can change them almost arbitrarily. They are pretty self explaining.
首先,我需要新建一些變量;你可以按照自己的意愿隨意修改。看變量的名稱大體上都能知道具體的意思。
- 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.
sOldText表示我要進(jìn)行搜索和替換的文本。tVisible只有在調(diào)試的時(shí)候才設(shè)置為true,這樣你可以看見(jiàn)具體的操作過(guò)程。tSaveOnExit為false直到我明確的進(jìn)行保存操作。
Now, we will open word and read the document as well as some base variables.
現(xiàn)在,我們將打開(kāi)word并且根據(jù)上面定義的基礎(chǔ)變量來(lái)讀取文檔的內(nèi)容。
- 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 should open word, but dont do something cool.
執(zhí)行上面代碼,將會(huì)打開(kāi)一個(gè)word,但是上面也不做。
oDocumentsholds the list of documents. oDocumentholds our specific document file_in.doc. oSelectionand oFindare objects we need for the next step, selecting and inserting.
oDocuments保存了文檔的列表(因?yàn)槭嵌辔臋n應(yīng)用程序)。oDocument被認(rèn)為是指定的文件file_in.doc. oSelection和 oFind是我們要進(jìn)行下一步操作的對(duì)象,主要用來(lái)進(jìn)行搜索和插入操作。
- Dispatch.put(oFind, "Text", sOldText);
- Dispatch.call(oFind, "Execute");
- Dispatch.put(oSelection, "Text", sNewText);
Now we search for sOldText, 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).
現(xiàn)在我們搜索sOldText內(nèi)容,執(zhí)行搜索語(yǔ)句,并且使用新的文本替代選中的項(xiàng)目。
So next, we leave that select stuff.
因此下一步,我們離開(kāi)選擇的東西。
- Dispatch.call(oSelection, "MoveDown");
- Dispatch.put(oSelection, "Text", " So we got the next line including BR. ");
We move the cursor down, effectively leaving the selection (yes, it works just like a VB macro inside Word; works also with MoveUp, MoveLeft, MoveRight). Then, we insert other text.
我們將光標(biāo)向下移動(dòng),有效的離開(kāi)選中的項(xiàng)目,然后開(kāi)始插入其他文本。(它工作起來(lái)類似于嵌入到word中的VB宏;使用起來(lái)有MoveUp, MoveLeft, MoveRight功能)
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).
現(xiàn)在我們希望格式化文本。我們一直采用的方式是先選中文本,然后進(jìn)行下一步操作,下面是具體的使用方法。
- 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 (the " So we got ... BR. ") 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. Using the MoveDownand Textdirectives you can do the basics.
現(xiàn)在對(duì)其是按照快的方式的(0代表左對(duì)齊,1是居中,2是右對(duì)齊,3是快對(duì)齊)?,F(xiàn)在這是對(duì)你有所幫助而要做的最少的事情,使用MoveDown和Text直接做你想做的事情。
保存和關(guān)閉
Well, there were a lot of suggestions on the mailing list, but that one worked for me.
在Jacob郵件列表里面有好多關(guān)于保存和關(guān)于的建議,但是這個(gè)是我使用的。
- Object oWordBasic = Dispatch.call(oWord, "WordBasic").getDispatch();
- Dispatch.call(oWordBasic, "FileSaveAs", sOutputDoc);
Dont ask me why. It just works.
不要問(wèn)我為什么,它確實(shí)是有效的。
- Dispatch.call(oDocument, "Close", newVariant(tSaveOnExit));
- oWord.invoke("Quit", newVariant[0]);
This is straigthforward. No sweat.
插入圖片
Yes its possible to embed images pretty easy.
使用Jacob來(lái)插入圖片是件很容易的事情。
- 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.
超鏈接的使用
Hyperlinks are also pretty straightforward (courtesy Kathrin Eichler, under Office XP):
超鏈接也可以非常完美的直接使用。
- 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.
表格
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.
到現(xiàn)在都沒(méi)有什么好的注意。我研究了VB代碼和其工作原理。我從郵件列表那里得到了一些建議,怎么去添加一行和越過(guò)一個(gè)表格,但是對(duì)于創(chuàng)建操作。。。。還是需要進(jìn)一步研究啊。
列表/枚舉
The VB code looks like shit. I have no idea how to work here. Still to come.
VB代碼看起來(lái)像一坨屎。到現(xiàn)在都沒(méi)有號(hào)的想法去實(shí)現(xiàn)怎么操作,還需要努力。
總結(jié)
上面是一個(gè)國(guó)外友人的文章,主要介紹了Jacob的使用方法,希望對(duì)有志于使用Java操作Word的童鞋有所幫助。
原文:http://www.cnblogs.com/rushoooooo/archive/2011/10/28/2227395.html
【編輯推薦】