当前位置:   article > 正文

JAVA根据模板生成Word文档_java根据word模板生成word文档

java根据word模板生成word文档

一、需要模板word文件和document.xml模板配置文件

首先把word文件重命名后缀改为.zip然后打开,就能在word文件夹下就能找到document.xml了

 在document.xml模板中需要赋值的地方配置好占位符。

 

 二、导入依赖,编写工具类

  1. <dependency>
  2. <groupId>org.freemarker</groupId>
  3. <artifactId>freemarker</artifactId>
  4. <version>2.3.28</version>
  5. </dependency>

GenerateWordUtils 工具类(对应路径自己修改) 

  1. package com.example.rabbitmq.util;
  2. import freemarker.template.Configuration;
  3. import freemarker.template.Template;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import java.io.*;
  7. import java.util.Enumeration;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.zip.ZipEntry;
  11. import java.util.zip.ZipFile;
  12. import java.util.zip.ZipOutputStream;
  13. public class GenerateWordUtils {
  14. private static Logger logger = LoggerFactory.getLogger(GenerateWordUtils.class);
  15. public static Configuration getConfiguration() throws IOException {
  16. Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
  17. //设置编码
  18. configuration.setDefaultEncoding("utf-8");
  19. //相对路径
  20. //configuration.setClassForTemplateLoading(GenerateWordUtils.class, "/templates");//此处设置模板存放文件夹名称
  21. //绝对路径
  22. configuration.setDirectoryForTemplateLoading(new File("D:\\S\\CMS\\rabbitmq\\src\\main\\resources\\templates"));//此处设置模板存放文件夹名称
  23. return configuration;
  24. }
  25. /**
  26. * 获取模板字符串输入流
  27. * @param dataMap 参数,键为绑定变量名,值为变量值
  28. * @param templateName 模板名称
  29. * @return
  30. */
  31. public static ByteArrayInputStream getFreemarkerContentInputStream(Map dataMap, String templateName) {
  32. ByteArrayInputStream in = null;
  33. try {
  34. Template template = getConfiguration().getTemplate(templateName);
  35. StringWriter swriter = new StringWriter();
  36. template.process(dataMap, swriter);
  37. //这里一定要设置utf-8编码 否则导出的word中中文会是乱码
  38. in = new ByteArrayInputStream(swriter.toString().getBytes("utf-8"));
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. logger.error("模板生成错误!");
  42. }
  43. return in;
  44. }
  45. //outputStream 输出流可以自己定义 浏览器或者文件输出流
  46. public static void createDocx(Map dataMap, OutputStream outputStream) {
  47. ZipOutputStream zipout = null;
  48. String docxPath="D:\\S\\CMS\\rabbitmq\\src\\main\\resources\\templates\\";
  49. try {
  50. //内容模板,传值生成新的文件输入流documentInput
  51. ByteArrayInputStream documentInput = GenerateWordUtils.getFreemarkerContentInputStream(dataMap, "document.xml");//xml模板文件名
  52. //最初设计的模板,原word文件生成File对象
  53. File docxFile = new File(docxPath+"demo1.docx");//word文件名称
  54. System.out.println(docxFile.exists());
  55. if (!docxFile.exists()) {
  56. docxFile.createNewFile();
  57. }
  58. ZipFile zipFile = new ZipFile(docxFile);//获取原word文件的zip文件对象,相当于解压缩了word文件
  59. // ZipFile zipFile = new ZipFile(docxPath+"demo1.zip");//获取原word文件的zip文件对象,相当于解压缩了word文件
  60. System.err.println(zipFile);
  61. Enumeration< ? extends ZipEntry> zipEntrys = zipFile.entries();//获取压缩文件内部所有内容
  62. zipout = new ZipOutputStream(outputStream);
  63. //开始覆盖文档------------------
  64. int len = -1;
  65. byte[] buffer = new byte[1024];
  66. while (zipEntrys.hasMoreElements()) {//遍历zip文件内容
  67. ZipEntry next = zipEntrys.nextElement();
  68. InputStream is = zipFile.getInputStream(next);
  69. if (next.toString().indexOf("media") < 0) {
  70. zipout.putNextEntry(new ZipEntry(next.getName()));//这步相当于创建了个文件,下面是将流写入这个文件
  71. if ("word/document.xml".equals(next.getName())) {//如果是word/document.xml由我们输入
  72. if (documentInput != null) {
  73. while ((len = documentInput.read(buffer)) != -1) {
  74. zipout.write(buffer, 0, len);
  75. }
  76. documentInput.close();
  77. }
  78. } else {
  79. while ((len = is.read(buffer)) != -1) {
  80. zipout.write(buffer, 0, len);
  81. }
  82. is.close();
  83. }
  84. }else{//这里设置图片信息,针对要显示的图片
  85. zipout.putNextEntry(new ZipEntry(next.getName()));
  86. while ((len = is.read(buffer)) != -1) {
  87. zipout.write(buffer, 0, len);
  88. }
  89. is.close();
  90. }
  91. }
  92. } catch (Exception e) {
  93. e.printStackTrace();
  94. logger.error("word导出失败:"+e.getStackTrace());
  95. }finally {
  96. if(zipout!=null){
  97. try {
  98. zipout.close();
  99. } catch (IOException e) {
  100. logger.error("io异常");
  101. }
  102. }
  103. if(outputStream!=null){
  104. try {
  105. outputStream.close();
  106. } catch (IOException e) {
  107. logger.error("io异常");
  108. }
  109. }
  110. }
  111. }
  112. public static void main(String[] args) throws FileNotFoundException {
  113. Map map=new HashMap<>();
  114. map.put("outWarehouseNo","1111");
  115. map.put("num","20");
  116. map.put("billLadingNo","20150200133");
  117. map.put("productName","小类");
  118. map.put("parentName","(大类)");
  119. map.put("quantityUnit","方");
  120. map.put("outQuantityNum","4543.56");
  121. map.put("clientName","客户1");
  122. map.put("repertoryName","zhongwen");
  123. map.put("year","2022");
  124. map.put("month","08");
  125. map.put("day","09");
  126. createDocx(map,new FileOutputStream("D:\\S\\CMS\\rabbitmq\\src\\main\\resources\\templates\\demo.docx"));
  127. }
  128. }

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/617117
推荐阅读
相关标签
  

闽ICP备14008679号