package org.word;
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class JacobUtil {
public static final int WORD_HTML = 8;
public static final int WORD_TXT = 7;
public static final int EXCEL_HTML = 44;
public static void wordToHtml(String docfile, String htmlfile) throws Exception {
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
try {
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[] { docfile, new Variant(false), new Variant(true) },
new int[1]).toDispatch();
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { htmlfile, new Variant(WORD_HTML) }, new int[1]);
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
File file = new File(htmlfile);
if (file.exists()) {
System.out.print("可读:");
System.out.println(file.canRead());
System.out.print("可写:");
System.out.println(file.canWrite());
System.out.print("可执行:");
System.out.println(file.canExecute());
} else {
System.out.println("file not found");
}
} catch (Exception e) {
throw e;
} finally {
app.invoke("Quit", new Variant[] {});
}
}
public static void excelToHtml(String xlsfile, String htmlfile) {
ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 启动Excel
try {
app.setProperty("Visible", new Variant(false));
Dispatch excels = app.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.invoke(excels, "Open", Dispatch.Method,
new Object[] { xlsfile, new Variant(false), new Variant(true) }, new int[1]).toDispatch();
Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] { htmlfile, new Variant(EXCEL_HTML) }, new int[1]);
Variant f = new Variant(false);
Dispatch.call(excel, "Close", f);
} catch (Exception e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
}
}
public static void main(String[] args) {
JacobUtil ju = new JacobUtil();
try {
ju.wordToHtml("e:\\TEST.docx", "e:\\TEST.html");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
P.S:文件 是指路径+文件名。。。
出现过的异常
1.原因:没有dll文件
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class JacobUtil {
}
P.S:文件 是指路径+文件名。。。
出现过的异常
1.原因:没有dll文件
Java代码
Exception in thread "main" java.lang.UnsatisfiedLinkError: no jacob in java.library.path
2. 原因:机子上没有装office
Java代码
cant get Object cldid from progid
相关文件:http://u.115.com/file/aq80atrq