jacob解决word

开发部的小弟问我如何把数据库的东西导出到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");
}
}


你可能感兴趣的:(jacob解决word)