1.首先去下载poi的基础库,下载地址:http://poi.apache.org/download.html
2.当前最高版本3.8 ,将poi-3.8-20120326.jar 和 poi-excelant-3.8-20120326.jar这两个文件加入到项目中
3.其他就是java的相关操作了,核心代码如下:
public void writeWord(HttpServletResponse response , ContractInput ci) { String URL = "F:/word/base.doc"; File file = new File(URL); try { FileInputStream in = new FileInputStream(file); POIFSFileSystem pfs = new POIFSFileSystem(in); HWPFDocument hwpf = new HWPFDocument(pfs); Range range = hwpf.getRange(); ci.replace(range); response.reset(); response.setContentType("application/x-msdownload"); String fileName = ci.getDistShow() + ci.getRealName();// response.addHeader("Content-Disposition", "attachment; filename=\""+new String(fileName.getBytes("gb2312"),"iso8859-1")+".doc\""); ByteArrayOutputStream ostream = new ByteArrayOutputStream(); ServletOutputStream servletOS = response.getOutputStream(); hwpf.write(ostream); servletOS.write(ostream.toByteArray()); servletOS.flush(); servletOS.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
ci.replace(range);处理替换信息,代码如下:
public String replace(Range range){ range.replaceText("丁培芳(身份证号码:xxxxx)", userInfo); range.replaceText("福建省 泉州市 晋江市", distShow); range.replaceText("贰", bzjStr); range.replaceText("400", maxFan); range.replaceText("10", commission); range.replaceText("丁培芳", realName); range.replaceText("dingpeifeng", userName); range .replaceText("13559582912", showMobel); return null; }