springboot配合Freemark模板生成word,前台vue接收并下载【步骤详解并奉上源码】

本文主要是介绍springboot配合Freemark模板生成word,前台vue接收并下载【步骤详解并奉上源码】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用fremmarker导出work 动态数据

  • 前言
  • 一、使用步骤
    • 1.打开word模板,给需要赋值的位置先填上数据,方便查找编写freemarker代码,如下图
    • 2.将word文件另存为xml文件 到桌面 ,然后修改jhj.xml修改后缀 改为 jhj.ftl 文件
  • 二、后台代码
    • 1.模板存放位置
    • 2.依赖引入
    • 3.后端代码
  • 3.前端vue 浏览器下载代码
  • 五、最后一步完成后 ,就是成果图的效果啦!


前言

FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。

成果图:
从浏览器直接下载到本地
在这里插入图片描述

下载好的word文件 蓝色圈圈里的数据均为动态数据
在这里插入图片描述

注:这里可以自行写word模板

一、使用步骤

1.打开word模板,给需要赋值的位置先填上数据,方便查找编写freemarker代码,如下图

在这里插入图片描述

2.将word文件另存为xml文件 到桌面 ,然后修改jhj.xml修改后缀 改为 jhj.ftl 文件

在这里插入图片描述
1.刚打开的xml文件会比较长不太方便查看 可以把内容复制到菜鸟工具进行格式化 找到之前做好标记的位置 将数据替换

在这里插入图片描述

2.list循环数据 : 在<w:tr> 前加上 <#list taskstep as taskstep> ** </w:tr>在这之后加上结束标签 </#list>

效果图

二、后台代码

1.模板存放位置

在这里插入图片描述

2.依赖引入

		<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.9</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>

3.后端代码

    @RequestMapping(value = "/Testrecord", method = RequestMethod.POST)@ResponseBodypublic ResponseEntity<byte[]>   Testrecord(@RequestBody Map<String, Object> paras, HttpServletRequest request) throws Exception {String path = request.getServletContext().getRealPath("/");//设备信息  获取数据BaseResult<Map<String, Object>> DeviceTask= deviceModuleService.getOneDeviceTask((Integer) paras.get("id"));//测试条件 获取数据BaseResult<List<DeviceTaskStep>> deviceTaskStepByParas = deviceModuleService.getDeviceTaskStepByParas(paras);List<DeviceTaskStep> taskstep = deviceTaskStepByParas.getData();//       循环方式BaseResult<List<DeviceTaskLoop>> deviceTaskLoopByParas = deviceModuleService.getDeviceTaskLoopByParas(paras);System.out.println(deviceTaskLoopByParas.getData().toString()+"SAD");List<DeviceTaskLoop> taskloop = deviceTaskLoopByParas.getData();
//        设备信息Map<String, Object> datataskstep = DeviceTask.getData();System.out.println(datataskstep);Object applyNo = datataskstep.get("reportNo");Configuration configuration = new Configuration();configuration.setDefaultEncoding("utf-8");// 模板存放路径configuration.setClassForTemplateLoading(this.getClass(), "/template");// 获取模板文件Template template = configuration.getTemplate("Testrecord.ftl");SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");Map<String,Object> resultMap = new HashMap<>();
//        设备信息  resultMap.put("reportno",datataskstep.get("reportNo"));//word加入单数据resultMap.put("devicename",datataskstep.get("deviceName"));resultMap.put("manufacturer",datataskstep.get("manufacturer"));resultMap.put("basictypename",datataskstep.get("basicTypeName"));resultMap.put("devicecode",datataskstep.get("deviceCode"));System.out.println();if(datataskstep.get("startTime")==null){resultMap.put("starttime"," ");}else {resultMap.put("starttime",datataskstep.get("startTime"));}if(datataskstep.get("endTime")==null){resultMap.put("endtime"," ");}else {resultMap.put("endtime",datataskstep.get("endTime"));}// 测试条件List<Map<String, Object>> tasksteps = new ArrayList<Map<String, Object>>();if (taskstep.size()==0){Map<String, Object> map=new HashMap<String, Object>();map.put("stepNum"," ");map.put("temp",  " ");map.put("humid",  " ");map.put("timeHour",  " ");map.put("timeMin", " ");tasksteps.add(map);}else {for (int i = 0; i < taskstep.size(); i++) {
//Map<String, Object> map=new HashMap<String, Object>();map.put("stepNum", taskstep.get(i).getStepNum());map.put("temp",  taskstep.get(i).getTemp());map.put("humid",  taskstep.get(i).getHumid());map.put("timeHour",  taskstep.get(i).getTimeHour());map.put("timeMin",  taskstep.get(i).getTimeMin());tasksteps.add(map);}}//        循环方式List<Map<String, Object>> taskloops = new ArrayList<Map<String, Object>>();//这里做一个判断  如果加入了空数据会报错if (taskloop.size()==0){Map<String, Object> map=new HashMap<String, Object>();map.put("loopNum", " ");map.put("stepStart", " ");map.put("stepStop", " ");map.put("loopCount",  " ");taskloops.add(map);}else {for (int i = 0; i < taskloop.size(); i++) {
//            System.out.println(taskloop.get(i).getTaskId()+"AAA");Map<String, Object> map=new HashMap<String, Object>();map.put("loopNum", taskloop.get(i).getLoopNum());map.put("stepStart",  taskloop.get(i).getStepStart());map.put("stepStop",  taskloop.get(i).getStepStop());map.put("loopCount",  taskloop.get(i).getLoopCount());taskloops.add(map);}}//word加入循环数据resultMap.put("taskstep",tasksteps);resultMap.put("taskloop",taskloops);
//        测试条件File outFile = new File(String.format("%s%s.%s",path,applyNo,"doc"));Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));template.process(resultMap,out);out.flush();out.close();//这是是绝对路径// String path = "C:\\Users\\zhangyf\\";// String filename = "aaa.doc";String filename = String.format("%s.%s",applyNo,"doc");File file = new File(path+filename);HttpHeaders headers = new HttpHeaders();//下载显示的文件名,解决中文名称乱码问题String downloadFileName = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);//通知浏览器以attachment(下载方式)打开图片headers.setContentDispositionFormData("attachment", downloadFileName);//application/octet-stream:二进制流数据(最常见的文件下载)headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//201 HttpStatus.CREATEDreturn new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);}

3.前端vue 浏览器下载代码

export function Testrecord(data) {return axios({url: '/h/deviceModule/Testrecord',method: 'post',data: data,responseType: 'blob' //这里改一下})
}
  // 导出测试结果模板hanldeExportTaskDoc(record) {const params = {id: record.id,taskId: record.id,}this.$api.Testrecord(params).then((res) => {if (res) {console.log(res);this.downloadWordFile(res,record.reportNo);}})},downloadWordFile (file,No) {console.log(No+'.docx');const blob = new Blob([file], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })const url = URL.createObjectURL(blob)const a = document.createElement('A')a.download = No+'.docx'  //下载的文件名  自行设置a.href = urldocument.body.appendChild(a)a.click()document.body.removeChild(a)},

五、最后一步完成后 ,就是成果图的效果啦!

这篇关于springboot配合Freemark模板生成word,前台vue接收并下载【步骤详解并奉上源码】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/242825

相关文章

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory