VUE+SpringBoot+EasyPoi实现浏览器点击下载word模板数据生成

本文主要是介绍VUE+SpringBoot+EasyPoi实现浏览器点击下载word模板数据生成,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

需求

模板

后台SpringBoot

pom.xml 

WordUtil

EntityUtils

Controller

Service

ServiceImpl

前台VUE

效果

参考官网


需求

现在有个需求,页面有个人员列表,需要点击旁边的个人简介下载他的word数据

模板

 首先我们先建立个word文件,格式为docx

要绑定的数据就是我们的实体类的字段名,{{}}格式绑定

将模板扔进项目资源

后台SpringBoot

pom.xml 

引入依赖

        <!-- 增加poi依赖--><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-spring-boot-starter</artifactId><version>4.3.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.4.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-web</artifactId><version>4.4.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-annotation</artifactId><version>4.4.0</version></dependency><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.12.0</version></dependency>

WordUtil

package com.cei.xyd_zgqx_back.utils;import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import com.cei.xyd_zgqx_back.entity.TExpertTraining;
import com.cei.xyd_zgqx_back.entity.vo.result.Result;
import com.cei.xyd_zgqx_back.entity.vo.result.ResultGenerator;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;@Component
public class WordUtil {/*** 导出word* <p>第一步生成替换后的word文件,只支持docx</p>* <p>第二步下载生成的文件</p>* <p>第三步删除生成的临时文件</p>* 模版变量中变量格式:{{name}}** @param map 实体类转Map* @param templatePath word模板地址* @param temDir       生成临时文件存放地址* @param request      HttpServletRequest* @param response     HttpServletResponse*/public static void exportWord(Map<String, Object> map, InputStream templatePath, String temDir, HttpServletRequest request, HttpServletResponse response) {Assert.notNull(templatePath, "模板路径不能为空");Assert.notNull(temDir, "临时文件路径不能为空");if (!temDir.endsWith("/")) {temDir = temDir + File.separator;}File dir = new File(temDir);if (!dir.exists()) {dir.mkdirs();}// 临时文件名String fileName = "temp.docx";try {XWPFDocument doc = new MyXWPFDocument(templatePath);WordExportUtil.exportWord07(doc, map);String tmpPath = temDir + fileName;FileOutputStream fos = new FileOutputStream(tmpPath);doc.write(fos);// 设置强制下载不打开response.setContentType("application/force-download");// 设置文件名response.setHeader("Content-Disposition", "attachment;filename*= UTF-8''"+ URLEncoder.encode(fileName,"UTF-8"));OutputStream out = response.getOutputStream();doc.write(out);fos.close();out.close();} catch (Exception e) {e.printStackTrace();} finally {// 这一步看具体需求,要不要删delFileWord(temDir, fileName);}}/*** 删除临时生成的文件*/public static void delFileWord(String filePath, String fileName) {// 读取临时文件File file = new File(filePath + fileName);// 删除文件file.delete();}
}

EntityUtils

package com.cei.xyd_zgqx_back.utils;import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;public class EntityUtils {/**** @description: 实体类转Map* @return*/public static Map<String, Object> entityToMap(Object object) {Map<String, Object> map = new HashMap<>();for (Field field : object.getClass().getDeclaredFields()) {try {boolean flag = field.isAccessible();field.setAccessible(true);Object o = field.get(object);map.put(field.getName(), o);field.setAccessible(flag);} catch (Exception e) {e.printStackTrace();}}return map;}
}

Controller

/*** */@PostMapping(value = "/exportExpertWord")public void exportExpertWord(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) throws PendingException {iSupplierService.exportExpertWord(json, request, response);}

Service

void exportExpertWord(String json, HttpServletRequest request, HttpServletResponse response);

ServiceImpl

这里面上面有些个人业务,酌情修改删除 

 步骤就是 >>>> 读取模板 >>>> 查询数据库数据 >>>> 模型结果转Map >>>> 传入Util导出

    @Overridepublic void exportExpertWord(String json, HttpServletRequest request, HttpServletResponse response) {JSONObject jsonObject = JSONObject.parseObject(json);// 当前登录供应商数据Integer orgId = (Integer) sign.get(SessionKey.SUPPLIER_ID.key());if (orgId == null) {
//            return ResultGenerator.genFailResult("未获取到当前登录供应商信息,请重新登录");}// 专家idInteger id = jsonObject.getInteger("id");if (id == null) {
//            return ResultGenerator.genFailResult("专家ID不能为空");}// 读取模板ClassPathResource classPathResource = new ClassPathResource("word/expertWord.docx");InputStream templatePath = null;try {templatePath = classPathResource.getInputStream();} catch (IOException e) {e.printStackTrace();}// 查询数据库,将数据传给导出TExpertTraining tExpertTraining = tExpertTrainingMapper.selectById(id);if (tExpertTraining == null) {
//            return ResultGenerator.genFailResult("未查询到此专家ID的数据");}// 实体转MapMap<String, Object> map = EntityUtils.entityToMap(tExpertTraining);// 导出wordWordUtil.exportWord(map, templatePath, "D:\\word", request, response);}

前台VUE

页面就好说了

请求的时候设置好responseTypeblob

下载的时候new Blob那注意后面type改成你要下载的文件格式类型,我那块是举例word 

// 下载专家个人简介worddownloadProfile(id, name) {const params = {id: id}this.$http.post('/supplier/exportExpertWord', params, {responseType: 'blob'},).then((response) => {// 为blob设置文件类型let blob = new Blob([response], {type: 'application/msword'});let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象let a = document.createElement("a");a.href = url;// 文件名a.download = name + '个人简介';a.click();// 释放这个临时的对象urlwindow.URL.revokeObjectURL(url);}).catch(() => {})},

效果

 点击下载文件出来了

打开文件数据也都接入到word模板里

参考官网

http://easypoi.mydoc.io/

这篇关于VUE+SpringBoot+EasyPoi实现浏览器点击下载word模板数据生成的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

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 声明式事物

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M