開發部的小弟問我如何把資料庫的東西匯出到word.
我覺得匯出到word是一個很愚蠢的做法.因為word的格式並不像excle或者html那樣好控制.但我還是給了他
一個方案.
由於微軟到現在都沒有公開word和excle的檔案格式,所以導致了java社區很多關於office的開源項目.
JXL,POI和JACOB應該是其中較著名的.
jxl主要用來對excle文檔進行操作.而poi和jacob則相對強大點.
jacob是採用的jni的方式,通過一個c++編寫的dll檔案來操作office文檔.為:http://danadler.com/jacob/index.html,直接下載它的最新版1.7版;
採用jacob的時候,除了需要把jacob.jar包含到classpath中,還需要把jacob.dll複製到system32目錄中.
有個helloworld的例子,關於寫word的:
/***********WordBean.java*****************/
/*
* 建立日期 2005-10-25
*
* TODO 要更改此產生的檔案的模板,請轉至
* 視窗 - 喜好設定 - Java - 代碼樣式 - 代碼模板
*/
package poitest;
import com.jacob.activeX.*;
import com.jacob.com.*;
public class WordBean extends java.awt.Panel
{
private ActiveXComponent MsWordApp = null;
private Dispatch document = null;
public WordBean()
{
super();
}
public void openWord(boolean makeVisible)
{
//Open Word if we/'ve not done it already
if (MsWordApp == null)
{
MsWordApp = new ActiveXComponent("Word.Application");
}
//Set the visible property as required.
Dispatch.put(MsWordApp, "Visible",new Variant(makeVisible));
}
public void createNewDocument()
{
//Find the Documents collection object maintained by Word
Dispatch documents = Dispatch.get(MsWordApp,"Documents").toDispatch();
//Call the Add method of the Documents collection to create
//a new document to edit
document = Dispatch.call(documents,"Add").toDispatch();
}
public void insertText(String textToInsert)
{
// Get the current selection within Word at the moment. If Rb8fnB
// a new document has just been created then this will be at ph
// the top of the new doc
Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch();
//Put the specified text at the insertion point
Dispatch.put(selection,"Text",textToInsert);
}
public void saveFileAs(String filename)
{
Dispatch.call(document,"SaveAs",filename);
}
public void printFile()
{
//Just print the current document to the default printer
Dispatch.call(document,"PrintOut");
}
public void closeDocument()
{
// Close the document without saving changes
// 0 = wdDoNotSaveChanges
// -1 = wdSaveChanges
// -2 = wdPromptToSaveChanges
Dispatch.call(document, "Close", new Variant(0));
document = null;
}
public void closeWord()
{
Dispatch.call(MsWordApp,"Quit");
MsWordApp = null;
document = null;
}
}
/************WordTest.java**********/
package jacobtest;
import java.io.File;
import com.jacob.com.*;
import com.jacob.activeX.*;
public class WordTest {
public static void main(String[] args) {
WordBean word=new WordBean();
word.openWord(true);
word.createNewDocument();
word.insertText("Hello word.");
//word.saveFileAs("e://testlcl.doc");
}
}