日期:2014-05-20 浏览次数:21002 次
//处理附件中的文件,在附件中加上邀请人的名字 ReplaceWord word = new ReplaceWord(); //循环发送邮件 for(int i = 0;i<names.length;i++){ mailbody = rebuildMailbody(mailbody_bak,names[i]); //处理附件中的文件,在附件中加上邀请人的名字 word.setDocPath(wordToReplace); word.setDocSaveAsPath(wordToSaveAs); word.setStrFind(wordStrFind); word.setStrReplace(names[i]); if(!word.replace()){ System.out.println("["+i+"] 附件文件处理失败!"); return; } System.out.print("["+(i+1)+"/"+names.length+"] "+names[i]+"..."); send(mail,strSmtpHost, username, password,addressFrom, address[i], addressCopy, addressDarkCopy,subject, mailbody, isNeedAuth, isNeedNotification); }
import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class ReplaceWord { private String docPath = ""; // 要处理的word文件的路径 private String docSaveAsPath = ""; // 处理后的文件另存为的路径(如果路径为空,则替换原有文件) private String strFind = ""; // 要查找的关键字 private String strReplace = ""; // 要替换的关键字 public ReplaceWord(String docPath, String docSaveAsPath, String strFind, String strReplace){ this.setDocPath(docPath); this.setDocSaveAsPath(docSaveAsPath); this.setStrFind(strFind); this.setStrReplace(strReplace); } public ReplaceWord(){ } public boolean replace() { boolean returnFlag = false; ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word String inFile = this.getDocPath(); // 要替换的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[] { inFile, new Variant(false), new Variant(true) }, // 以只读方式打开word new int[1]).toDispatch(); Dispatch selection = app.getProperty("Selection").toDispatch();// 获得对Selection组件 Dispatch.call(selection, "HomeKey", new Variant(6));// 移到开头 Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 获得Find组件 Dispatch.put(find, "Text", this.getStrFind()); // 查找字符串 Dispatch.call(find, "Execute"); // 执行查询 Dispatch.put(selection, "Text", this.getStrReplace()); // 替换字符串 if(this.getDocSaveAsPath() == null || this.getDocSaveAsPath().length() == 0){ Dispatch.call(doc, "Save"); // 保存文件 } else{ Dispatch.call(doc, "SaveAs",this.getDocSaveAsPath()); // 文件另存为 } //close document without saving changes Dispatch.call(doc, "Close", new Variant(0)); returnFlag = true; } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); returnFlag = false; } finally { app.invoke("Quit", new Variant[]{}); app.safeRelease(); } return returnFlag; } // some getters and setters }