1.下载jacob,http://sourceforge.net/projects/jacob-project/
2.安装office软件(jacob只能运行在window系统上)
3.将jacob.jar复制到工程lib下,将jacob-xxxx.dll复制到JAVA_HOME\bin目录下
一、word转html
public static final int WORD_HTML = 8;
public static final int WORD_TXT = 7;
public static final int EXCEL_HTML = 44;
public static boolean wordToHtml(String fileDoc, String fileHtml) {
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
try {
// 设置word不可见
app.setProperty("Visible", new Variant(false));
// 获得documents对象
Dispatch docs = (Dispatch) app.getProperty("Documents")
.toDispatch();
// 打开文件
Dispatch doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { fileDoc, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
// 保存新的文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
fileHtml, new Variant(WORD_HTML) }, new int[1]);
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
app.invoke("Quit", new Variant[] {});
}
}
二、word转PDF
private static final int NOTSAVECHANGE = 0;
private static final int PDF = 17;
public static void wordToPDF(String fileDoc, String filePDF) {
ActiveXComponent app = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs,"Open",fileDoc,false,true).toDispatch();
//读取全文内容
Dispatch content = Dispatch.get(doc, "Content").toDispatch();
String text = Dispatch.get(content, "Text").toString();
File f = new File(filePDF);
if (f.exists()) {
f.delete();
}
Dispatch.call(doc,"SaveAs",filePDF,PDF);
Dispatch.call(doc, "Close", false);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (app != null){
app.invoke("Quit", NOTSAVECHANGE);
}
}
}