maven pom文件引入jar
<!-- velocity --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> </dependency>版本号,任意
导出方法如下
/** * 导出word并下载 * * @author wangdongdong * * @param response * @param request * @param params 传入的参数map * @param fileName 生成的文件名 * @param templateFileName 模板文件名 */ public static void exportToWordDownload(HttpServletResponse response, HttpServletRequest request, Map<String, Object> params, String fileName, String templateFileName) { OutputStream outputStream = null; try { WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request); String webRoot = ctx.getServletContext().getRealPath("/");
// 获取绝对路径 String filePath = webRoot + File.separator + "WEB-INF" + File.separator + "template" + File.separator; outputStream = response.getOutputStream(); response.reset(); // 防止文件名乱码 String agent = request.getHeader("USER-AGENT"); if (agent.indexOf("MSIE") >= 0) { URLCodec codec = new URLCodec(); fileName = codec.encode(fileName, "UTF-8"); fileName = StringUtils.replace(fileName, "+", "%20"); } else { fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); } response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\""); response.setContentType("application/x-msdownload"); createDocAndDownload(params, filePath, templateFileName, outputStream); } catch (Exception ex) { logger.error(ex.getMessage()); } finally { IOUtils.closeQuietly(outputStream); } } /** * 生成word并下载 * @param dataMap * @param templatePath * @param templateFileName * @param os * @throws Exception */ private static void createDocAndDownload(Map<String, Object> dataMap, String templatePath, String templateFileName, OutputStream os) throws Exception { VelocityContext velocityContext = new VelocityContext(); for (String key : dataMap.keySet()) { velocityContext.put(key, dataMap.get(key)); } // 设置路径参数 Properties properties = new Properties(); // 这是模板所在路径 properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templatePath); VelocityEngine velocityEngine = new VelocityEngine(); // 初始化 velocityEngine.init(properties); velocityEngine.init(); // 加载模板 Template template = velocityEngine.getTemplate(templateFileName, "UTF-8"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "utf-8")); template.merge(velocityContext, writer); writer.flush(); }将制作好的word模板,另存为xml格式的文件
打开,将需要替换的文字,改用传入的对象字段
调用方法,并且将map里面放入doctorName
exportToWordDownload()
生成如下文件: