public boolean writeWordFile(Map<String,String> writeMap){
boolean flag = false;
ActiveXComponent word = null;
if(this.wordFile!=null){
try{
//1获得worfFile对象
word = new ActiveXComponent("Word.Application");
Dispatch dispatchTarget = word.getProperty("Documents").toDispatch();
String name = "Open";
int wFlags = Dispatch.Method;
//是否进行转换 ConfirmConversions : new Variant(true)
//是否只读 :new Variant(false)
Object[] oArg = new Object[]{this.wordFile.getPath(),new Variant(true),new Variant(false)};
int[] uArgErr = new int[1];
Dispatch wordfile = Dispatch.invoke(dispatchTarget, name, wFlags, oArg, uArgErr).toDispatch();
//2获得选择器对象
Dispatch vSelection = word.getProperty("Selection").toDispatch();
//3获得表对象
Dispatch tables = Dispatch.get(wordfile, "tables").toDispatch();
//3
for (String loc : writeMap.keySet()) {
String[] locs = loc.split(",");
int a = Integer.parseInt(locs[0]);
int b = Integer.parseInt(locs[1]);
int c = Integer.parseInt(locs[2]);
try{
//4获得cell
Dispatch table = Dispatch.call(tables, "Item", new Variant(a)).toDispatch();
Dispatch cell = Dispatch.call(table, "Cell", new Variant(b),new Variant(c)).toDispatch();
//5获得数据
Dispatch range=Dispatch.get(cell,"Range").toDispatch();
String data=Dispatch.get(range,"Text").getString();
if(data.length()>=2){
data = data.substring(0, data.length()-2);
}
if(data.length()>0
&&!data.endsWith("\r")){
data=data+"\r";
}
//6选中cell,并添加数据
Dispatch.call(cell, "Select");
Dispatch.put(vSelection, "Text", data+writeMap.get(loc));
}catch(Exception e){
continue;
}
}
Dispatch.call(wordfile, "Close", new Variant(-2));
flag = true;
}catch(Error e){
if("java.lang.NoClassDefFoundError".equals(e.getClass().getName())){
if("Could not initialize class com.jacob.activeX.ActiveXComponent".equals(e.getMessage())){
LOG.error("word文档中插入意见失败:请将jacob-1.14.3-x86.dll文件放入java.library.path[url=\""+System.getProperty("java.home")+"\\bin\\\"]后重启web服务器");
}else{
LOG.error("相关文档:java后台编辑word文件表格内容的功能开发备忘录、升级说明、使用说明_20141020.doc",e);
}
}else{
LOG.error("相关文档:java后台编辑word文件表格内容的功能开发备忘录、升级说明、使用说明_20141020.doc",e);
}
}catch(Exception e){
LOG.error("相关文档:java后台编辑word文件表格内容的功能开发备忘录、升级说明、使用说明_20141020.doc",e);
}finally{
if(word!=null){
word.safeRelease();
Dispatch.call(word, "Quit");
}
ComThread.Release();
}
}else{
System.out.println("initWordFile 办事不利:未生成word文件");
}
return flag;
}
问题:
运行一次 任务管理器中就多一个winword.exe。
网上有说:ComThread.Release(); word.safeRelease(); 都没用
执行Dispatch.call(word, "Quit");