用到的包在這裡下載http://danadler.com/jacob/, 將jacob.jar,jacob.dll 的路徑寫入CLASSPATH
環境變數,下面是我調試通過的程式:
import com.jacob.com.*;
import com.jacob.activeX.*;
import java.io.*;
//取得指定目錄下面所有的doc檔案名稱
public class WordtoHtml
{
//------------------------------------------------------------------------------
//方法原型: change(String paths)
//功能描述: 將指定目錄下面所有的doc檔案轉化為HTML並儲存在相同目錄下
//輸入參數: String
//輸出參數: 無
//返 回 值: 無
//其它說明: 遞迴
//------------------------------------------------------------------------------
public static void change(String paths, String savepaths)
{
File d = new File(paths);
//取得當前檔案夾下所有檔案和目錄的列表
File lists[] = d.listFiles();
String pathss = new String("");
for(int i = 0; i < lists.length; i ++)
{
if(lists[i].isFile())
{
String filename = lists[i].getName();
String filetype = new String("");
//取得檔案類型
filetype = filename.substring((filename.length() - 3), filename.length());
//判斷是否為doc檔案
if(filetype.equals("doc"))
{
System.out.println("當前正在轉換......");
//列印目前的目錄路徑
System.out.println(paths);
//列印doc檔案名稱
System.out.println(filename.substring(0, (filename.length() - 4)));
ActiveXComponent app = new ActiveXComponent("Word.Application");//啟動word
String docpath = paths + filename;
String htmlpath = savepaths + filename.substring(0, (filename.length() - 4));
String inFile = docpath;
//要轉換的word檔案
String tpFile = htmlpath;
//HTML檔案
boolean flag = false;
try
{
app.setProperty("Visible", new Variant(false));
//設定word不可見
Object docs = app.getProperty("Documents").toDispatch();
Object doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{inFile,new Variant(false), new Variant(true)}, new int[1]).toDispatch();
//開啟word檔案
Dispatch.invoke(doc,"SaveAs", Dispatch.Method, new Object[]{tpFile,new Variant(8)}, new int[1]);
//作為html格式儲存到臨時檔案
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
flag = true;
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
app.invoke("Quit", new Variant[] {});
}
System.out.println("轉化完畢!");
}
}
else
{
System.out.print("Folder");
pathss = paths;
//進入下一級目錄
pathss = pathss + lists[i].getName() + "//";
//遞迴遍曆所有目錄
change(pathss, savepaths);
}
}
}
//------------------------------------------------------------------------------
//方法原型: main(String[] args)
//功能描述: main檔案
//輸入參數: 無
//輸出參數: 無
//返 回 值: 無
//其它說明: 無
//------------------------------------------------------------------------------
public static void main(String[] args)
{
String paths = new String("E://Project//");
String savepaths = new String ("D://javapro//");
change(paths,savepaths);
}
}