首先要下载JACOB
下载地址:http://sourceforge.net/projects/jacob-project/
下载Jacob的发布包,里面应该包含一个jar包:jacob.jar(放在项目的classpath下)
两个dll文件:jacob-1.15-M4-x64.dll、jacob-1.15-M4-x86.dll
两个dll文件请根据系统架构属性选择其中一个
Tomcat服务器:放入Tomcat ~/bin 目录下
WebLogic服务器:放入 Oracle/Middleware/wlserver_10.3/server/bin 目录下
代码如下:
//系统路径 String path = request.getSession().getServletContext().getRealPath(""); //资源存放路径 String sourcePath = path + "/template/download/"; String wordFileName = chartStatic.WORDNAME+wordMap.get("year").toString()+".doc"; String wordFilePath = sourcePath+wordFileName; //初始文件地址 ActiveXComponent MsWordApp = null; Dispatch document = null; ComThread.startMainSTA();//启动一个主线程 ComThread.InitMTA(true); MsWordApp = new ActiveXComponent("Word.Application"); Dispatch documents = MsWordApp.getProperty("Documents").toDispatch(); //打开文档 document = Dispatch.call(documents, "Open", wordFilePath).toDispatch(); //获取书签 Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch(); Dispatch rangeItem = null; Dispatch range = null;
装配数据到Word
//装配文字 setDispatch(chartStatic.SR_DATA_END,wordMap.get(chartStatic.SR_DATA_END).toString(),bookMarks); //装配图片 setDispatchImages(chartStatic.SR_IMG_BAR,filenameBar,bookMarks);
两个封装方法
/** * 把数据放入对应的书签 * @param bookmarkName word 中的书签名 * @param bookmarkValue 把值插入此数千名中 * @param bookMarks 所有的书签名 * @return */ private boolean setDispatch(String bookmarkName,String bookmarkValue,Dispatch bookMarks){ Dispatch rangeItem = null; Dispatch range = null; boolean bookMarkExist = Dispatch.call(bookMarks, "Exists", bookmarkName).getBoolean(); if(bookMarkExist){ //替换文字 rangeItem = Dispatch.call(bookMarks, "Item", bookmarkName).toDispatch(); range = Dispatch.call(rangeItem, "Range") .toDispatch(); //替换文字 Dispatch.put(range, "Text", new Variant(bookmarkValue)); } return bookMarkExist; } /** * 把图片放入对应的书签中 * * @param bookmarkName * word中的标签名 * @param picFileName * 图片路径 * @param bookMarks * 所有标签名 * @return */ private boolean setDispatchImages(String bookmarkName,String picFileName,Dispatch bookMarks){ Dispatch rangeItem = null; Dispatch range = null; boolean bookMarkExist = Dispatch.call(bookMarks, "Exists", bookmarkName).getBoolean(); if(bookMarkExist){ rangeItem = Dispatch.call(bookMarks,"Item", bookmarkName).toDispatch(); range = Dispatch.call(rangeItem, "Range").toDispatch(); //生成图片 File imgfile = new File(System.getProperty("java.io.tmpdir"), picFileName); //替换图片 Dispatch picture = Dispatch.call(Dispatch.get(range,"InLineShapes").toDispatch(),"AddPicture", imgfile.getAbsolutePath()).toDispatch(); } return bookMarkExist; }
保存,关闭文件。
//保存,关闭文件 if (document != null) { Dispatch.call(document, "Save"); Dispatch.call(document, "Close", new Variant(0)); } if (MsWordApp != null) { MsWordApp.invoke("Quit", new Variant[0]); } ComThread.Release();//释放 ComThread.quitMainSTA();//关闭
保存为Html
//保存为html Dispatch.invoke(document,"SaveAs",Dispatch.Method, new Object[]{htmlFile, new Variant(8)},//7为txt格式, 8保存为html格式 new int[1]);
效果图如下