首先参考的是这篇文章:

java利用Freemarker模板生成docx格式的word文档(全过程) - 旁光 - 博客园参考:https://my.oschina.net/u/3737136/blog/2958421?tdsourcetag=s_pcqq_aiomsg 具体思路 1.创建一个docx文档模板,其中的英文https://www.cnblogs.com/ssyh/p/12494626.html我这次是通过Freemarker模板生成一个申请表,内容如下:

1.先使用word把这个模板编写好,这要注意后缀为.docx

2.将这个文件的后缀改为.zip,然后解压在word目录下找到document.xml如下:

3.将他复制到idea中格式化代码(内容非常多,格式化后好找)后修改,把name改为${name},其他也是一样:

4.pom中导入依赖:

<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId></dependency>

5.编写工具类FreeMarkUtils:

public class FreeMarkUtils {private static Logger logger = LoggerFactory.getLogger(FreeMarkUtils.class);public static Configuration getConfiguration(){//创建配置实例Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);//设置编码configuration.setDefaultEncoding("utf-8");configuration.setClassForTemplateLoading(FreeMarkUtils.class, "/templates");//换成自己对应的目录return configuration;}/*** 获取模板字符串输入流* @param dataMap   参数* @param templateName  模板名称* @return*/public static ByteArrayInputStream getFreemarkerContentInputStream(Map dataMap, String templateName) {ByteArrayInputStream in = null;try {//获取模板Template template = getConfiguration().getTemplate(templateName);StringWriter swriter = new StringWriter();//生成文件template.process(dataMap, swriter);in = new ByteArrayInputStream(swriter.toString().getBytes("utf-8"));//这里一定要设置utf-8编码 否则导出的word中中文会是乱码} catch (Exception e) {logger.error("模板生成错误!");}return in;}
}

6.编写controller:FreemarkerController

@Controller
public class FreemarkerController {@ResourceShenqingDao shenqingDao;private static String document= "document.xml";/*** 导出申请表** @param id* @return*/@RequestMapping("manage/dc")@ResponseBodypublic ResultUtil dc(Integer id) {try {Shenqing shenqing = shenqingDao.queryById(id);System.out.println(shenqing);Map dataMap=new HashMap();dataMap.put("xueyuan", shenqing.getXueyuan());dataMap.put("zhuanye", shenqing.getZhuanye());dataMap.put("classname", shenqing.getClassname());dataMap.put("name", shenqing.getName());dataMap.put("gender", shenqing.getGender());dataMap.put("birthday", shenqing.getBirthday());dataMap.put("jiguan", shenqing.getJiguan());dataMap.put("idnum", shenqing.getIdnum());dataMap.put("familynum", shenqing.getFamilynum());dataMap.put("tel", shenqing.getTel());dataMap.put("addr", shenqing.getAddr());dataMap.put("youbian", shenqing.getYoubian());dataMap.put("familytel", shenqing.getFamilytel());dataMap.put("Intro", shenqing.getIntro());dataMap.put("yyijian", shenqing.getYyijian());dataMap.put("yijian", shenqing.getXyijian());//指定输出docx路径File outFile = new File("C:\\Users\\dyb\\IdeaProjects\\zizhu\\src\\main\\resources\\templates\\家庭经济困难学生认定申请表.docx") ;createDocx(dataMap,new FileOutputStream(outFile));return ResultUtil.ok("导出申请表成功");} catch (Exception e) {return ResultUtil.error("导出申请表,稍后再试!");}}//outputStream 输出流可以自己定义 浏览器或者文件输出流public static void createDocx(Map dataMap, OutputStream outputStream) {ZipOutputStream zipout = null;try {/*//图片配置文件模板ByteArrayInputStream documentXmlRelsInput = FreeMarkUtils.getFreemarkerContentInputStream(dataMap, documentXmlRels);*///内容模板ByteArrayInputStream documentInput = FreeMarkUtils.getFreemarkerContentInputStream(dataMap, document);//最初设计的模板//File docxFile = new File(WordUtils.class.getClassLoader().getResource(template).getPath());File docxFile = new File("C:\\Users\\dyb\\IdeaProjects\\zizhu\\src\\main\\resources\\templates\\家庭经济困难学生认定申请表(模版).zip");//换成自己的zip路径if (!docxFile.exists()) {System.out.println(111111);docxFile.createNewFile();}ZipFile zipFile = new ZipFile(docxFile);Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();zipout = new ZipOutputStream(outputStream);//开始覆盖文档------------------int len = -1;byte[] buffer = new byte[1024];while (zipEntrys.hasMoreElements()) {ZipEntry next = zipEntrys.nextElement();InputStream is = zipFile.getInputStream(next);if (next.toString().indexOf("media") < 0) {zipout.putNextEntry(new ZipEntry(next.getName()));if ("word/document.xml".equals(next.getName())) {//如果是word/document.xml由我们输入if (documentInput != null) {while ((len = documentInput.read(buffer)) != -1) {zipout.write(buffer, 0, len);}documentInput.close();}} else {while ((len = is.read(buffer)) != -1) {zipout.write(buffer, 0, len);}is.close();}}}} catch (Exception e) {System.out.println("word导出失败:"+e.getStackTrace());//logger.error();}finally {if(zipout!=null){try {zipout.close();} catch (IOException e) {System.out.println("io异常");}}if(outputStream!=null){try {outputStream.close();} catch (IOException e) {System.out.println("io异常");}}}}
}

7.前端:

<a class="layui-btn layui-btn-warm  layui-btn-xs" lay-event="dc">导出申请表</a>layer.confirm('确定导出?', function (index) {$.ajax({url: ctx + '/manage/dc?id=' + data.id,type: "get",success: function (d) {if (d.code == 0) {layer.msg(d.msg, {icon: 1});table.reload('userinfoList', {})} else {layer.msg("操作失败,请重试", {icon: 5});}}})layer.close(index);});

项目结构:

最后的效果:

springboot结合Freemarker模板生成docx格式的word文档(附代码)相关推荐

  1. java利用Freemarker模板生成docx格式的word文档(全过程)

    参考汇总: wordexport: JAVA生成并导出Word文档技术论证 java利用Freemarker模板生成docx格式的word文档(全过程) - 旁光 - 博客园 # 参考资料 - 其他项 ...

  2. java生成docx_java利用Freemarker模板生成docx格式的word文档

    之前写过一篇利用Freemarker模板生成doc的博客,不过那个博客有点缺陷,生成的word占用的空间很大,几百页的word有将近100M了.所以,后面需求必须是生成的docx文档,结果导出后正常才 ...

  3. Django在线预览docx格式的word文档

    Django在线预览docx格式的word文档 第一步 明确功能是:预览word的docx文件. 具体实现是:在Django的模板文件中,定义预览方法:read_word2html from pydo ...

  4. 如何批量将 Doc 格式的 Word 文档转为 Docx 格式

    概要:我们都知道 Word 格式有多种.比如常见的有 Doc.Docx,这两种类型是能够相互兼容的,也是能够相互转化的.那今天给大家介绍的是如何将多个 Doc 格式文档批量转为 Docx 格式. 我们 ...

  5. 执法文书打印的实现(二):基于freemaker技术生成可打印的word文档

    执法文书打印的实现(二)     基于freemaker技术生成可打印的word文档: 基于FreeMarker生成word.doc文档是一项比较成熟的技术.前承上篇博客(),这个方案只能在windo ...

  6. Java 将xml模板动态填充数据转换为word文档

    需要用到的jar包: commons-codec-1.10.jar freemarker-2.3.21.jar jacob-1.6.jar 实现思路: 1.先将word文档另存为 : Word 200 ...

  7. 如何在Python中将数据插入到Word模板中生成一份Word文档

    在一些的项目开发中,会有一些生成Word文件的操作,比如将获取到的一些数据添加到Word模板当中的相应的位置生成一份Word文档. 由于最近的Python项目当中需要将一些从服务器查出的数据添加到Wo ...

  8. 如何将PDF格式转换为WORD文档

    经常在PDF形式上看到有好的文件时,想把它拿出来,但是却是不行,所以我第一步就是找一下有没有可以到PDF格式与WORD文档的转换,在网上找了一下,原来还真的有很多,今天我就把这些方法也传上来,不过我也 ...

  9. Python3-word文档操作(十):利用docx库创建word文档,添加段落,添加表格,添加图片,设置文字粗体,斜体

    1 简介: 作为一个综合例子,本篇主要显示docx库的一些基本操作: 利用docx库创建word文档,添加段落,添加表格,添加图片,设置文字粗体,斜体. 2 举例: 对word文档进行属性的设置,以及 ...

最新文章

  1. 初探系列 — Pharbers用于单点登录的权限架构
  2. python游戏编程入门-python游戏编程入门
  3. 在brew开发中遇到的一些问题
  4. Seam开发环境的搭建
  5. 程序员的数学全三册密码_阿波罗50年前成功登月,少不了这位硬核女程序员
  6. Django(part11)--MTV模式及模板
  7. 如何使用eclemma插件_如何集成和使用EclEmma插件来获得良好的Junit覆盖率
  8. python tkinter实例_Python tkinter模版代码实例
  9. ipv6单播地址包括哪两种类型_探秘联接|技术小课堂之BRAS设备IPv6地址分配方式...
  10. php中的代码延迟函数sleep() usleep()
  11. 检测VC++Redistributable运行库 vcredist_x86.exe
  12. tayga nat64优化的自省揭示tun虚拟网卡的正确玩法
  13. 查询-非等值连接,外连接,子查询
  14. 工程总承包(EPC)最高投标限价政策解说
  15. 网络安全论文投稿给电脑编程技巧与维护有哪些要求
  16. Todesk一直显示正在连接本地连接
  17. Linux运维高级核心基础
  18. 前端搭建小人逃脱游戏(内附源码)
  19. vivo s12参数
  20. echart旭日图_ECharts 旭日图

热门文章

  1. 震惊!十六岁少女竟然被三名阿里p8老师讲解{常见面试题汇总}
  2. 游戏服务器架构设计的一些整理
  3. 鸿蒙系统拟物化图标,那些让人不得不吐槽的软件设计风格
  4. 【黄敏聪|自由设计师系列1-基础篇】教程之二 |自由设计师走向成功最佳策略是什么?
  5. 量化分析师的Python日记【第3天:一大波金融Library来袭之numpy篇】
  6. C# Winfrom学生管理系统
  7. JedisConnectionException: java.net.SocketException: Broken pipe (Write failed)
  8. ae渲染存在偏移_(图文+视频)C4D+AE野教程:一起来制作一个MG方块动画吧
  9. 重点知识学习(8.2)--[JMM(Java内存模型),并发编程的可见性\原子性\有序性,volatile 关键字,保持原子性,CAS思想]
  10. 论文阅读Super Edge 4-Points Congruent Sets-Based Point Cloud Global Registration