当前位置: 首页 > news >正文

Java填充Execl模板并返回前端下载

功能:后端使用Java POI填充Execl模板,并返回前端下载

Execl模板如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/b07f29d50c1243d4bdc9919381815a68.png

1. Java后端

功能:填充模板EXECL,并返回前端

controller层

package org.huan.controller;import org.huan.dto.ExcelData;
import org.huan.util.ExcelTemplateFiller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;@Controller
public class ExcelController {@PostMapping("/generateExcel")@ResponseBodypublic ResponseEntity<byte[]> generateExcel(@RequestBody ExcelData excelData) {// You'll need to modify the parameters and logic here based on your object and requirements// For example:String templateFilePath = "C:\\Users\\lenovo\\Desktop\\aa\\a.xlsx";String outputFilePath = "C:\\Users\\lenovo\\Desktop\\aa\\output.xlsx";// Generate Excel file based on the received objectExcelTemplateFiller.execl(templateFilePath, outputFilePath, excelData);try {// Read the generated filePath path = Paths.get(outputFilePath);byte[] fileContent = Files.readAllBytes(path);// Create a ResponseEntity with the file content as bodyHttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));headers.setContentDispositionFormData("attachment", "output.xlsx");headers.setContentLength(fileContent.length);return ResponseEntity.ok().headers(headers).body(fileContent);} catch (Exception e) {e.printStackTrace();return ResponseEntity.badRequest().body(null);}}
}

ExcelTemplateFiller POI填充表格

package org.huan.util;import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.huan.dto.ExcelData;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;public class ExcelTemplateFiller {public static void main(String[] args) {String templateFilePath = "C:\\Users\\lenovo\\Desktop\\aa\\a.xlsx";String outputFilePath = "C:\\Users\\lenovo\\Desktop\\aa\\output.xlsx";//execl(templateFilePath, outputFilePath);}public static void execl(String templateFilePath, String outputFilePath, ExcelData excelData) {try (InputStream templateInputStream = Files.newInputStream(Paths.get(templateFilePath));Workbook workbook = new XSSFWorkbook(templateInputStream)) {Sheet sheet = workbook.getSheetAt(0);//全 称sheet.getRow(8).getCell(27).setCellValue(excelData.getFullName());//账号sheet.getRow(10).getCell(27).setCellValue(excelData.getAccountNumber());//开户机构sheet.getRow(12).getCell(27).setCellValue(excelData.getAccountInstitution());//人民币(大写)sheet.getRow(14).getCell(7).setCellValue(excelData.getRmbInWords());//十 亿 千 百 十 万 千 百 十 元 角 分// 十亿, 亿, 千万, 百万, 十万, 万, 千, 百, 十, 元, 角, 分Row row = sheet.getRow(15);row.getCell(30).setCellValue(excelData.getBillion());row.getCell(31).setCellValue(excelData.getHundredMillion());row.getCell(32).setCellValue(excelData.getTenMillion());row.getCell(33).setCellValue(excelData.getMillion());row.getCell(34).setCellValue(excelData.getHundredThousand());row.getCell(35).setCellValue(excelData.getTenThousand());row.getCell(36).setCellValue(excelData.getThousand());row.getCell(37).setCellValue(excelData.getHundred());row.getCell(38).setCellValue(excelData.getTen());row.getCell(39).setCellValue(excelData.getYuan());row.getCell(40).setCellValue(excelData.getJiao());row.getCell(41).setCellValue(excelData.getFen());//用途sheet.getRow(16).getCell(7).setCellValue(excelData.getPurpose());//备注sheet.getRow(17).getCell(7).setCellValue(excelData.getRemark());try (FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath)) {workbook.write(fileOutputStream);}System.out.println("Data has been filled into the Excel template successfully!");} catch (Exception e) {e.printStackTrace();}}
}

实体类

package org.huan.dto;import lombok.Data;@Data
public class ExcelData {private String fullName;private String accountNumber;private String accountInstitution;private String rmbInWords;private String billion;private String hundredMillion;private String tenMillion;private String million;private String hundredThousand;private String tenThousand;private String thousand;private String hundred;private String ten;private String yuan;private String jiao;private String fen;private String purpose;private String remark;}

pom依赖

    <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.14</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.14</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.14</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.14</version></dependency>

2. VUE前端

功能:
2.1 利用Vue过滤器实现 Vue数字金额转大写
2.2 点击按钮下载后端 EXECl

<span>{{model.balance | toChies(amount)}}</span>
<template><div><button @click="downloadExcel">Download Excel</button></div>
</template><script>
export default {data() {return {excelData: {fullName: 'John Doe',accountNumber: '1234567890',accountInstitution: 'ABC Bank',rmbInWords: 'One Thousand Yuan',billion: '1',hundredMillion: '1',tenMillion: '1',million: '1',hundredThousand: '1',tenThousand: '1',thousand: '1',hundred: '1',ten: '1',yuan: '1',jiao: '1',fen: '1',purpose: 'Purchase',remark: 'No remarks',},};};},filters:{toChies(amount){// 汉字的数字const cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];// 基本单位const cnIntRadice = ["", "拾", "佰", "仟"];// 对应整数部分扩展单位const cnIntUnits = ["", "万", "亿", "兆"];// 对应小数部分单位const cnDecUnits = ["角", "分"];// 整数金额时后面跟的字符const cnInteger = "整";// 整型完以后的单位const cnIntLast = "元";// 最大处理的数字const maxNum = 9999999999999999.99;// 金额整数部分let integerNum;// 金额小数部分let decimalNum;// 输出的中文金额字符串let chineseStr = "";// 分离金额后用的数组,预定义let parts;if (amount === "") {return "";}amount = parseFloat(amount);if (amount >= maxNum) {// 超出最大处理数字return "";}if (amount === 0) {chineseStr = cnNums[0] + cnIntLast + cnInteger;return chineseStr;}// 转换为字符串amount = amount.toString();if (amount.indexOf(".") === -1) {integerNum = amount;decimalNum = "";} else {parts = amount.split(".");integerNum = parts[0];decimalNum = parts[1].substr(0, 4);}// 获取整型部分转换if (parseInt(integerNum, 10) > 0) {let zeroCount = 0;const IntLen = integerNum.length;for (let i = 0; i < IntLen; i++) {const n = integerNum.substr(i, 1);const p = IntLen - i - 1;const q = p / 4;const m = p % 4;if (n === "0") {zeroCount++;} else {if (zeroCount > 0) {chineseStr += cnNums[0];}// 归零zeroCount = 0;//alert(cnNums[parseInt(n)])chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];}if (m === 0 && zeroCount < 4) {chineseStr += cnIntUnits[q];}}chineseStr += cnIntLast;}// 小数部分if (decimalNum !== "") {const decLen = decimalNum.length;for (let i = 0; i < decLen; i++) {const n = decimalNum.substr(i, 1);if (n !== "0") {chineseStr += cnNums[Number(n)] + cnDecUnits[i];}}}if (chineseStr === "") {chineseStr += cnNums[0] + cnIntLast + cnInteger;} else if (decimalNum === "") {chineseStr += cnInteger;}return chineseStr;}
},methods: {const formattedAmount = this.$options.filters.toChies(this.excelData.rmbInWords);downloadExcel() {this.excelData = { rmbInWords: formattedAmount ...};axios({url: 'http://your-backend-url/generateExcel', // Replace with your backend endpointmethod: 'POST',responseType: 'blob', // Specify response type as blob to handle binary datadata: this.excelData,}).then((response) => {const url = window.URL.createObjectURL(new Blob([response.data]));const link = document.createElement('a');link.href = url;link.setAttribute('download', 'output.xlsx'); // Set the file name heredocument.body.appendChild(link);link.click();}).catch((error) => {console.error('Error downloading Excel:', error);});},
};</script>

相关文章:

Java填充Execl模板并返回前端下载

功能&#xff1a;后端使用Java POI填充Execl模板&#xff0c;并返回前端下载 Execl模板如下&#xff1a; 1. Java后端 功能&#xff1a;填充模板EXECL,并返回前端 controller层 package org.huan.controller;import org.huan.dto.ExcelData; import org.huan.util.ExcelT…...

ChatGPT本地部署,学习记录

一、GPT4ALL模型 官网地址&#xff1a; Github&#xff1a;https://github.com/nomic-ai/gpt4all GPT4ALL项目部署简易&#xff0c;但是在运行体验上一般&#xff0c;并且是只调用CPU来进行运算。 看官方文档介绍在嵌入式上有比较大的优势&#xff0c;但是目前个人对嵌入式…...

Find My游戏手柄|苹果Find My技术与手柄结合,智能防丢,全球定位

游戏手柄是一种常见电子游戏机的部件&#xff0c;通过操纵其按钮等&#xff0c;实现对游戏虚拟角色的控制。随着游戏设备硬件的升级换代&#xff0c;现代游戏手柄又增加了&#xff1a;类比摇杆&#xff08;方向及视角&#xff09;&#xff0c;扳机键以及HOME菜单键等。现在的游…...

2024美赛数学建模思路 - 复盘:光照强度计算的优化模型

文章目录 0 赛题思路1 问题要求2 假设约定3 符号约定4 建立模型5 模型求解6 实现代码 建模资料 0 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 1 问题要求 现在已知一个教室长为15米&#xff0c;宽为12米&…...

【Deep Dive: AI Webinar】开放 ChatGPT - 人工智能开放性运作的案例研究

【深入探讨人工智能】网络研讨系列总共有 17 个视频。我们按照视频内容&#xff0c;大致上分成了 3 个大类&#xff1a; 1. 人工智能的开放、风险与挑战&#xff08;4 篇&#xff09; 2. 人工智能的治理&#xff08;总共 12 篇&#xff09;&#xff0c;其中分成了几个子类&…...

Devops相关问题及答案(2024)

1、DevOps 的理念是什么&#xff1f; DevOps是一种组织文化、流程和工具的集合&#xff0c;旨在提高软件交付的速度和质量&#xff0c;通过自动化和持续改进的方法来促进开发&#xff08;Dev&#xff09;和运维&#xff08;Ops&#xff09;的协作。 DevOps的核心理念包括&…...

掌握Python设计模式,SQL Alchemy打破ORM与模型类的束缚

大家好&#xff0c;反转软件组件之间的依赖关系之所以重要&#xff0c;是因为它有助于降低耦合度和提高模块化程度&#xff0c;进而可以提高软件的可维护性、可扩展性和可测试性。 当组件之间紧密耦合时&#xff0c;对一个组件的更改可能会对其他组件产生意想不到的影响&#…...

性能分析与调优: Linux 磁盘I/O 观测工具

目录 一、实验 1.环境 2.iostat 3.sar 4.pidstat 5.perf 6. biolatency 7. biosnoop 8.iotop、biotop 9.blktrace 10.bpftrace 11.smartctl 二、问题 1.如何查看PSI数据 2.iotop如何安装 3.smartctl如何使用 一、实验 1.环境 &#xff08;1&#xff09;主机 …...

Could not erase files or folders:

IDEA删除 git 的 localChanges 内的文件时&#xff0c;提示Could not erase files or folders:。 确认下这个文件是否被打开&#xff0c;忘记关闭了&#xff1b;关闭后可以被删除。&#xff08;文件被打开的情况下&#xff0c;用操作系统自带的删除&#xff0c;也无法删除成功…...

算法训练营第四十四天|动态规划:完全背包理论基础 518.零钱兑换II 377. 组合总和 Ⅳ

目录 动态规划&#xff1a;完全背包理论基础Leetcode518.零钱兑换IILeetcode377. 组合总和 Ⅳ 动态规划&#xff1a;完全背包理论基础 文章链接&#xff1a;代码随想录 题目链接&#xff1a;卡码网&#xff1a;52. 携带研究材料 思路&#xff1a;完全背包问题&#xff0c;物品可…...

探索计算机网络:应用层的魅力

在当今数字化时代&#xff0c;计算机网络已成为我们生活和工作中不可或缺的一部分。网络的每一层都扮演着独特而重要的角色&#xff0c;而应用层&#xff0c;作为网络模型中用户最直接接触的部分&#xff0c;其重要性不言而喻。这篇文章旨在深入探索应用层的核心概念、功能以及…...

MySQL 按日期流水号 条码 分布式流水号

有这样一个场景&#xff0c;有多台终端&#xff0c;要获取唯一的流水号&#xff0c;流水号格式是 日期0001形式&#xff0c;使用MySQL的存储过程全局锁实现这个需求。 以下是代码示例。 注&#xff1a;所有的终端连接到MySQL服务器获取流水号&#xff0c;如果获取到的是 “-1”…...

前端导出Excel文件,部分数字前面0消失处理办法

详细导出可以看之前的文章 js实现导出Excel文档_js 通过 接口 导出 xlsx 代码-CSDN博客 今天的问题是导出一些数据时&#xff0c;有些字段是前面带有0的字符串&#xff0c;而导出后再excel中就被识别成了数字 如图本来字符串前面的0 都没了 解决方案 1. 导出的时候在前面加单…...

零基础学Python网络爬虫案例实战 全流程详解 高级进阶篇

零基础学Python网络爬虫案例实战 全流程详解 入门与提高篇 零基础学Python网络爬虫案例实战 全流程详解 高级进阶篇 编辑推荐 本书讲解了Python爬虫技术的高级进阶知识&#xff0c;帮助有一定爬虫基础的读者进一步提高爬虫技术。本书详解了突破反爬机制的常用手段以及Scrapy和…...

第十二届“中关村青联杯”全国研究生数学建模竞赛-A题:水面舰艇编队防空和信息化战争评估模型(续)(附MATLAB代码实现)

目录 5.3.3 问题三的总结 5.4 问题四的模型建立与求解 5.4.1 问题分析 5.4.2 计算方位角和航向角...

bmp图像文件格式超详解

0 BMP简介 BMP(Bitmap-File)图形文件&#xff0c;又叫位图文件&#xff0c;是Windows采用的图形文件格式&#xff0c;在Windows环境下运行的所有图像处理软件都支持BMP图像文件格式。Windows系统内部各图像绘制操作都是以BMP为基础的。一个BMP文件由四部分组成&#xff1a; B…...

Unity Meta Quest 一体机开发(十三):【手势追踪】自定义交互事件 EventWrapper

文章目录 &#x1f4d5;教程说明&#x1f4d5;交互事件概述&#x1f4d5;自定义交互逻辑⭐方法一&#xff1a;Inspector 面板赋值⭐方法二&#xff1a;纯代码处理 此教程相关的详细教案&#xff0c;文档&#xff0c;思维导图和工程文件会放入 Spatial XR 社区。这是一个高质量…...

13、Redis高频面试题

1、项目中为什么用Redis 我们项目中之所以选择Redis&#xff0c;主要是因为Redis有下面这些优点&#xff1a; 操作速度快&#xff1a;Redis的数据都保存在内存中&#xff0c;相比于其它硬盘类的存储&#xff0c;速度要快很多数据类型丰富&#xff1a;Redis支持 string&#x…...

Koa学习笔记

1、npm 初始化 npm init -y生成 package.json 文件,记录项目的依赖2、git 初始化 git init生成 .git 隐藏文件夹,.git 的本地仓库创建 .gitignore 文件,添加不提交文件的名称3、创建 ReadMe.md 文件 记录项目笔记4、搭建项目 安装 Koa 框架npm install koa5、编写最基本的…...

HiDataPlus 3.3.2-005 搭建(个人的一点心得体会 x86 平台)

HDP 集群搭建 前置安装 yum -y install createrepo yum install -y lrzsz yum install -y wget yum install -y vim修改当前集群机器的主机名 hostnamectl set-hostname XXX​ 这里的 XXX 就是要设置的当前机器的主机名称。主机名称是集群唯一的&#xff0c;一定不要重复&am…...

Python|GIF 解析与构建(5):手搓截屏和帧率控制

目录 Python&#xff5c;GIF 解析与构建&#xff08;5&#xff09;&#xff1a;手搓截屏和帧率控制 一、引言 二、技术实现&#xff1a;手搓截屏模块 2.1 核心原理 2.2 代码解析&#xff1a;ScreenshotData类 2.2.1 截图函数&#xff1a;capture_screen 三、技术实现&…...

React第五十七节 Router中RouterProvider使用详解及注意事项

前言 在 React Router v6.4 中&#xff0c;RouterProvider 是一个核心组件&#xff0c;用于提供基于数据路由&#xff08;data routers&#xff09;的新型路由方案。 它替代了传统的 <BrowserRouter>&#xff0c;支持更强大的数据加载和操作功能&#xff08;如 loader 和…...

PPT|230页| 制造集团企业供应链端到端的数字化解决方案:从需求到结算的全链路业务闭环构建

制造业采购供应链管理是企业运营的核心环节&#xff0c;供应链协同管理在供应链上下游企业之间建立紧密的合作关系&#xff0c;通过信息共享、资源整合、业务协同等方式&#xff0c;实现供应链的全面管理和优化&#xff0c;提高供应链的效率和透明度&#xff0c;降低供应链的成…...

1688商品列表API与其他数据源的对接思路

将1688商品列表API与其他数据源对接时&#xff0c;需结合业务场景设计数据流转链路&#xff0c;重点关注数据格式兼容性、接口调用频率控制及数据一致性维护。以下是具体对接思路及关键技术点&#xff1a; 一、核心对接场景与目标 商品数据同步 场景&#xff1a;将1688商品信息…...

转转集团旗下首家二手多品类循环仓店“超级转转”开业

6月9日&#xff0c;国内领先的循环经济企业转转集团旗下首家二手多品类循环仓店“超级转转”正式开业。 转转集团创始人兼CEO黄炜、转转循环时尚发起人朱珠、转转集团COO兼红布林CEO胡伟琨、王府井集团副总裁祝捷等出席了开业剪彩仪式。 据「TMT星球」了解&#xff0c;“超级…...

鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院查看报告小程序

一、开发环境准备 ​​工具安装​​&#xff1a; 下载安装DevEco Studio 4.0&#xff08;支持HarmonyOS 5&#xff09;配置HarmonyOS SDK 5.0确保Node.js版本≥14 ​​项目初始化​​&#xff1a; ohpm init harmony/hospital-report-app 二、核心功能模块实现 1. 报告列表…...

BCS 2025|百度副总裁陈洋:智能体在安全领域的应用实践

6月5日&#xff0c;2025全球数字经济大会数字安全主论坛暨北京网络安全大会在国家会议中心隆重开幕。百度副总裁陈洋受邀出席&#xff0c;并作《智能体在安全领域的应用实践》主题演讲&#xff0c;分享了在智能体在安全领域的突破性实践。他指出&#xff0c;百度通过将安全能力…...

JDK 17 新特性

#JDK 17 新特性 /**************** 文本块 *****************/ python/scala中早就支持&#xff0c;不稀奇 String json “”" { “name”: “Java”, “version”: 17 } “”"; /**************** Switch 语句 -> 表达式 *****************/ 挺好的&#xff…...

Maven 概述、安装、配置、仓库、私服详解

目录 1、Maven 概述 1.1 Maven 的定义 1.2 Maven 解决的问题 1.3 Maven 的核心特性与优势 2、Maven 安装 2.1 下载 Maven 2.2 安装配置 Maven 2.3 测试安装 2.4 修改 Maven 本地仓库的默认路径 3、Maven 配置 3.1 配置本地仓库 3.2 配置 JDK 3.3 IDEA 配置本地 Ma…...

AI,如何重构理解、匹配与决策?

AI 时代&#xff0c;我们如何理解消费&#xff1f; 作者&#xff5c;王彬 封面&#xff5c;Unplash 人们通过信息理解世界。 曾几何时&#xff0c;PC 与移动互联网重塑了人们的购物路径&#xff1a;信息变得唾手可得&#xff0c;商品决策变得高度依赖内容。 但 AI 时代的来…...