注:機器或服務器上裝有word
首先需要有jacob.dll和jacob.jar
將jacob.dll放在system32和myeclipse的bin目錄下
將jacob.jar放在工程的lib目錄下
然後進行編碼操作
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordToHtml
{
/**
* 文檔轉換函數
* @param docfile
* @param htmlfile
*/
public static void change(String docfile, String htmlfile)
{
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 啓動word
try
{
app.setProperty("Visible", new Variant(false));
// 設置word不可見
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();
// 打開word文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
htmlfile, new Variant(8) }, new int[1]);
// 作爲html格式保存到臨時文件
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
app.invoke("Quit", new Variant[] {});
}
}
{
/**
* 文檔轉換函數
* @param docfile
* @param htmlfile
*/
public static void change(String docfile, String htmlfile)
{
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 啓動word
try
{
app.setProperty("Visible", new Variant(false));
// 設置word不可見
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();
// 打開word文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
htmlfile, new Variant(8) }, new int[1]);
// 作爲html格式保存到臨時文件
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
app.invoke("Quit", new Variant[] {});
}
}
public static void main(String[] strs)
{
WordToHtml.change("夏新test.docx", "夏新test.html");
}
}
{
WordToHtml.change("夏新test.docx", "夏新test.html");
}
}