由于项目开发需要,产品给出word模板,需要导出该格式的word文件。
1.通过word模板文件生成我们需要的模板.ftl文件。
步骤:将word文件转换成Microsoft XML格式文件(打开word,文件另存为xml格式文件),用notepad++编辑器打开文件,修改文件里面的内容,具体数据用${参数}替换,全部替换完成以后,将文件的后缀名改成.ftl,文件格式。
2.将生成好的文件放到项目相应的目录下,便于后面读取使用。
3.后台实现逻辑:
try { Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("title", "测试"); resultMap.put("keyword", "导出word"); // 生成Word文档 File file = WordGenerator.createDoc(resultMap, "template"); InputStream fin = new FileInputStream(file); response.setCharacterEncoding("utf-8"); response.setContentType("application/msword"); // 设置浏览器以下载的方式处理该文件 response.addHeader("Content-Disposition", "attachment;filename=" + "\"" + new String(fileName.getBytes(), "iso-8859-1") + ".doc"); ServletOutputStream out = response.getOutputStream(); // 缓冲区 byte[] buffer = new byte[512]; int bytesToRead = -1; while ((bytesToRead = fin.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); } out.flush(); if (fin != null) { fin.close(); } if (out != null) { out.close(); } if (file != null) { // 删除临时文件 file.delete(); } } catch (Exception e) { e.printStackTrace(); }
createDoc方法:通过模板和输入数据dataMap,生成临时word文件,再通过浏览器下载该文件。
public static File createDoc(Map<?, ?> dataMap, String type) { // 临时文件名称 String name = "temp" + (int) (Math.random() * 100000) + ".doc"; // 临时文件存储路径 String tempFileDir = PropertiesUtil.getValueByKey("path");//临时文件存储路径 File fileMkDir = new File(tempFileDir); // 如果文件夹不存在则创建 if (!fileMkDir.exists() && !fileMkDir.isDirectory()) { fileMkDir.mkdir(); } File file = new File(tempFileDir, name); // 获取模板 Template template = allTemplates.get(type); try { Writer out = null; FileOutputStream fos = null; fos = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); out = new BufferedWriter(writer); template.process(dataMap, out); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } return file; }
模板初始化:
private static Configuration configuration = null; private static Map<String, Template> allTemplates = null; static { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(WordGenerator.class, "/download"); allTemplates = new HashMap<String, Template>(); try { Template template = configuration.getTemplate("template.ftl","UTF-8"); Template template1 = configuration.getTemplate("template1.ftl", "UTF-8"); Template template2 = configuration.getTemplate("template1.ftl", "UTF-8"); allTemplates.put("template", template); allTemplates.put("template1", template1); allTemplates.put("template2",template2); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }
本方法是基于任意word模板实现相应导出的实现模式,因此较直接导出word相对来说复杂一点,但是能满足任意导出样式。