调度word程序,错误格式的word文件,避免弹出选择打开方式的窗口
package com.rw.tools.Word2Excel.Utility;
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordConverter {
private static final int DOCX_FMT = 12;
private Logger log = LoggerFactory.getLogger(getClass());
public WordConverter() {
}
public File convert2Docx(String srcPath, String descPath) throws Exception {
return convertDocFormat(srcPath, descPath, DOCX_FMT);
}
public File convertDocFormat(String srcPath, String descPath, int fmt) throws Exception {
// 实例化ComThread线程与ActiveXComponent
ComThread.InitSTA();
ActiveXComponent app = new ActiveXComponent("Word.Application");
try {
// 文档隐藏时进行应用操作
app.setProperty("Visible", new Variant(false));
// 实例化模板Document对象
Dispatch document = app.getProperty("Documents").toDispatch();
// 打开Document进行另存为操作
// Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method,
// new Object[] { srcPath, new Variant(true), new Variant(true) }, new int[1]).toDispatch();
//这是主要的控制修改调度方式参数,当打开word失败时不进行弹框,避免导致程序的等待
Dispatch doc = Dispatch.invoke(document,"Open",Dispatch.Method,
new Object[]{srcPath,
new Variant(false),
new Variant(true),//是否只读
new Variant(false)},new int[1]).toDispatch();
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { descPath, new Variant(fmt) }, new int[1]);
Dispatch.call(doc, "Close", new Variant(false));
return new File(descPath);
} catch (Exception e) {
throw e;
} finally {
// 释放线程与ActiveXComponent
app.invoke("Quit", new Variant[] {});
ComThread.Release();
}
}
public static void main(String[] args) {
WordConverter dfc = new WordConverter();
String srcDocPath = "D://MH.docx";
String descDocPath = "D://MH-1.docx";
try {
dfc.convertDocFormat(srcDocPath, descDocPath, DOCX_FMT);
} catch (Exception e) {
e.printStackTrace();
}
}
}