import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
*
* @FileName FileExtracter.java
* @author dinguangx blog: http://hi.baidu.com/dinguangx
* @date <Apr 15, 2009> <2:12:26 PM> @
* <p>
* company: www.zzuli.edu.cn
* </p>
* @version GDMS v1.0
*/
public class JavaConWord {
/**
* 将源word文件转换为html文件.进行转换之后,就可以在网页中直接引用这个html文件
*
* @param srcFileName
* @param destFileName
* @return
*/
public static boolean doc2Html(String srcFileName, String destFileName) {
if (srcFileName == null || "".equals(srcFileName.trim()))
throw new IllegalStateException("文件名不能为空");
if (destFileName == null || "".equals(destFileName.trim()))
throw new IllegalStateException("文件名不能为空");
boolean flag = false;
// 取得文件类型
srcFileName = srcFileName.trim();
destFileName = destFileName.trim();
String srcFiletype = new String();
srcFiletype = srcFileName.substring((srcFileName.length() - 3),
srcFileName.length());
String destFiletype = new String();
destFiletype = destFileName.substring((destFileName.length() - 4),
destFileName.length());
// 判断源文件是否为doc文件
if (!"doc".equals(srcFiletype))
throw new IllegalStateException("错误的文件格式!");
// 判断目录文件是否为html文件
if (!"html".equals(destFiletype))
throw new IllegalStateException("错误的文件格式!");
// 打印doc文件名
System.out
.println(srcFileName.substring(0, (srcFileName.length() - 4)));
// 启动word
ActiveXComponent app = new ActiveXComponent("Word.Application");
try {
app.setProperty("Visible", new Variant(false));
// 设置word不可见
Object docs = app.getProperty("Documents").toDispatch();
Object doc = Dispatch.invoke((Dispatch) docs, "Open",
Dispatch.Method, new Object[] { srcFileName }, new int[1])
.toDispatch();
// 打开word文件
Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method,
new Object[] { destFileName, new Variant(8) }, new int[1]);
// 作为html格式保存到临时文件
Variant f = new Variant(false);
Dispatch.invoke((Dispatch) doc, "Close", Dispatch.Method,
new Object[] { f }, new int[1]);
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
}
System.out.println("转化完毕!");
return flag;
}
public static void main(String[] args) {
System.out.println(doc2Html("G://test.doc", "g:/test.html"));
}
}
还要下载jacob 建议用1.9版本以上,把jacob.jar放到工程lib包下,把jacob.dll放入操作系统C:/WINDOWS/system32下
这里的jacob是指jacob.dll文件,其解决办法是把jacob.dll文件拷贝到 jre/bin 目录和jre/lib/ext目录下 |