java+springmvc实现根据freemarker模板导出word模板。模板使用的后缀可以是:.xml,也可以是.ftl。
步骤1,引入freemarker的jar包。
步骤2,制作模板文件。(红框中的内容是为了替换使用)
另存为xml格式,
找到xml文件,右键用editplus打开,找到红框的标记1,标记2进行修改。
如果是表格的话,表头的第一行需要保留。
表格的主体部分需要保留一个,
这里eList是从后台赋值的一个集合,${e_index+1}是根据<#list eList as e>这个别名+_index得到,用法基本与el表达式用法相同。
这样一个模板就完成了,将模板复制进项目中即可,后缀是什么不重要,重要的是我们用freemarker解析。
步骤4,java后台代码。
@RequestMapping("/test/toWord") public ModelAndView toWord(HttpServletRequest request, HttpServletResponse response) throws IOException{ File file = createDoc(); response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("UTF-8"); java.io.BufferedInputStream bis = null; java.io.BufferedOutputStream bos = null; try { long fileLength = file.length(); response.setContentType("application/msword"); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("测试的,统计-导出时间"+DateTimeUtils.getDateTime("yyyyMMddHHmmss")+".doc", "utf-8")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(file)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } return null; } private File createDoc(){ // 创建数据 Map<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put("cwlx", "测试的"); List<?> eList = new ArrayList<?>();// 这里是获取list列表的方法 dataMap.put("czsj",DateTimeUtils.getDateTime("yyyyMMddHHmmss"));// 这里是获取当前时间的一种方式,可以根据自己程序自行修改 dataMap.put("eList", eList); // 获取模板 Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(this.getClass(), "/tpl"); Template t = null; String name = "temp"+(int)(Math.random()*1000)+".doc"; File file = new File(name); try { t = configuration.getTemplate("model.xml"); t.setEncoding("UTF-8"); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name),"UTF-8")); t.process(dataMap, out); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } return file; }
在前台页面是需要做的就是发送一个链接就可以了。
特别注意,
经常忽视的问题,编码的问题,这里需要统一编码。
如果出现了word文件不能打开的情况,建议看一下后台文件是否报错。如果后台没有报错的话,建议用editplus打开word的文档,查看文档中是否有乱码的情况。
笔者第一次使用的时候,经常出现word文件不能打开的问题,于是我在editplus中打开,发现部分汉字是乱码的,加了上图红框中的默认编码的设置之后就可以了。
以上代码是本人亲测过的,可以放心使用。如有不明白的地方,欢迎交流。如有不正确的地方或累赘的地方也可以互相交流。