环境配置:
下载jacob.rar,解压出jacob.dll和jacob.jar,然后:
1) 把jacob.dll在 C:\Program Files\Java\jdk1.5.0_08\bin、C:\Program Files\Java\jdk1.5.0_08\jre\bin、C:\WINDOWS\system32 目录下各.放一份
2) 把jacob.jar放入 项目的lib包下,并且在“java构建路径”中也要加载此jar包。.
package com.kettas;
import com.jacob.activeX.*;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordtoHtml {
/**
* WORD转HTML
*
* @param docfilePath
* WORD文件全路径
* @param htmlfilePath
* 转换后HTML存放路径
*/
public void wordToHtml(String docfilePath, String htmlfilePath) {
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
try {
app.setProperty("Visible", new Variant(false)); // 设置word为不可视
Dispatch dispatch = app.getProperty("Documents").toDispatch(); // 读取文档属性值
Dispatch doc = Dispatch.invoke(
dispatch,
"Open",
Dispatch.Method,
new Object[] { docfilePath, new Variant(false),
new Variant(true) }, new int[1]).toDispatch(); // 功能调用
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
htmlfilePath, new Variant(8) }, new int[1]); // 以html格式保存到临时文件
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f); // 将文档关闭,并将其设置为不可视
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* EXCEL转HTML
* @param xlsfile EXCEL文件全路径
* @param htmlfile 转换后HTML存放路径
*/
public static void excelToHtml(String xlsfile, String htmlfile) {
// 启动excel
ActiveXComponent app = new ActiveXComponent("Excel.Application");
try {
//设置excel不可见
app.setProperty("Visible", new Variant(false));
Dispatch excels = app.getProperty("Workbooks").toDispatch();
//打开excel文件
Dispatch excel = Dispatch.invoke(
excels,
"Open",
Dispatch.Method,
new Object[] { xlsfile, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
//作为html格式保存到临时文件
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) {
WordtoHtml wth = new WordtoHtml(); // 创建本类对象
wth.wordToHtml("d:\\d.docx", "c:\\向word中绘制表格.html"); // 调用格式转换方法
}
}