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

相关文章

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Java中如何正确的停掉线程

《Java中如何正确的停掉线程》Java通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置