Java-web利用模板文件实现导出自定义word文档

由于项目开发需要,产品给出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相对来说复杂一点,但是能满足任意导出样式。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以的,基于aspose.word自定义word模板实现java导出动态word的步骤如下: 1. 首先,需要在Java项目中引入aspose.word的依赖。 2. 接着,需要准备好自定义word模板,可以使用Microsoft Word进行制作。在制作模板时,需要将需要动态填充的位置标记出来,例如使用${}来标记。 3. 在Java代码中,使用aspose.word提供的API读取自定义word模板,并且使用aspose.word提供的API将需要填充的数据填入模板中。 4. 最后,将填充好数据的word文件输出即可。 以下是示例代码: ```java // 加载自定义word模板 Document doc = new Document("自定义word模板.docx"); // 获取需要填充的位置 NodeCollection<Node> nodes = doc.getChildNodes(NodeType.RUN, true); // 填充数据,这里使用了HashMap作为数据源,实际开发中可以根据实际情况使用其他数据源 HashMap<String, String> data = new HashMap<String, String>(); data.put("name", "张三"); data.put("age", "25"); data.put("address", "北京市朝阳区"); for (Node node : nodes) { Run run = (Run) node; String text = run.getText().trim(); if (text.startsWith("${") && text.endsWith("}")) { String key = text.substring(2, text.length() - 1); if (data.containsKey(key)) { run.setText(data.get(key)); } } } // 输出填充好数据的word文件 doc.save("填充好数据的word文件.docx"); ``` 以上代码演示了如何使用aspose.word自定义word模板实现java导出动态word
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值