velocity根据模板导出word并下载工具方法

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()
生成如下文件:

要根据Word模板灵活导出Java代码,可以使用Apache POI、FreeMarker和Velocity等开源库来实现。具体步骤如下: 1. 使用Apache POI读取Word模板文件,获取模板中的内容。 2. 使用FreeMarker或Velocity模板引擎,根据需要生成需要填充的数据。 3. 将生成的数据填充到Word模板中,生成最终的Word文档。 以下是实现的简单示例代码: ``` // 读取Word模板文件 FileInputStream fis = new FileInputStream("template.docx"); XWPFDocument doc = new XWPFDocument(fis); // 获取模板中的内容 List<XWPFParagraph> paragraphs = doc.getParagraphs(); List<XWPFTable> tables = doc.getTables(); // 使用FreeMarker生成数据 Configuration cfg = new Configuration(Configuration.VERSION_2_3_0); cfg.setDefaultEncoding("UTF-8"); cfg.setClassForTemplateLoading(this.getClass(), "/templates"); Map<String, Object> data = new HashMap<>(); data.put("name", "张三"); data.put("age", 20); Template template = cfg.getTemplate("template.ftl"); StringWriter writer = new StringWriter(); template.process(data, writer); String content = writer.toString(); // 使用Velocity生成数据 VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("name", "张三"); context.put("age", 20); StringWriter writer = new StringWriter(); ve.evaluate(context, writer, "", template); String content = writer.toString(); // 将生成的数据填充到Word模板中 for (XWPFParagraph paragraph : paragraphs) { String text = paragraph.getText(); if (text.contains("${")) { text = text.replaceAll("\\$\\{.*?\\}", content); paragraph.setText(text); } } for (XWPFTable table : tables) { List<XWPFTableRow> rows = table.getRows(); for (XWPFTableRow row : rows) { List<XWPFTableCell> cells = row.getTableCells(); for (XWPFTableCell cell : cells) { String text = cell.getText(); if (text.contains("${")) { text = text.replaceAll("\\$\\{.*?\\}", content); cell.setText(text); } } } } // 保存最终的Word文档 FileOutputStream fos = new FileOutputStream("output.docx"); doc.write(fos); fos.close(); ``` 以上代码仅供参考,具体实现还需要根据实际需求进行调整。使用模板引擎可以更加灵活地生成数据,根据不同的模板生成不同的数据,从而实现灵活导出Word文档的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值