首先制定word模板,改成你需要的样子。格式如下,$需要变量名称$。使用poi。
从前台传值过来:window.location.href = basePath + '**.do?id='+encodeURI(encodeURI(id, "UTF-8"),"UTF-8");
//获取模板文件的目录地址
String path = request.getSession().getServletContext().getRealPath("/");
String fileDir = new File(path+"jsp/templet/").getCanonicalPath();
//获取模板文件
File demoFile=new File(fileDir + "/doc.doc");
FileInputStream in = new FileInputStream(demoFile);
HWPFDocument hdt = new HWPFDocument(in);
//替换读取到的word模板内容的指定字段
Range range = hdt.getRange();
Map<String, String> map = new HashMap<String, String>();
map.put("$BIANMA$", SSCID);
map.put("$DENAME$", DNAME);
map.put("$DATE$", now.get(Calendar.YEAR)+"年"+(now.get(Calendar.MONTH) + 1)+"月"+now.get(Calendar.DAY_OF_MONTH)+"日");
for (Map.Entry<String,String> entry:map.entrySet()) {
range.replaceText(entry.getKey(),entry.getValue());
}
//输出word内容文件流,提供下载
response.setContentType("application/x-msdownload");
String name = java.net.URLEncoder.encode(DNAME+".doc", "UTF8");
name = new String((name).getBytes("UTF-8"), "ISO-8859-1");
response.addHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'"+name);
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
ServletOutputStream servletOS = response.getOutputStream();
hdt.write(ostream);
servletOS.write(ostream.toByteArray());
servletOS.flush();
servletOS.close();