当前位置: 首页 > 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…...

FFmpeg 低延迟同屏方案

引言 在实时互动需求激增的当下&#xff0c;无论是在线教育中的师生同屏演示、远程办公的屏幕共享协作&#xff0c;还是游戏直播的画面实时传输&#xff0c;低延迟同屏已成为保障用户体验的核心指标。FFmpeg 作为一款功能强大的多媒体框架&#xff0c;凭借其灵活的编解码、数据…...

前端导出带有合并单元格的列表

// 导出async function exportExcel(fileName "共识调整.xlsx") {// 所有数据const exportData await getAllMainData();// 表头内容let fitstTitleList [];const secondTitleList [];allColumns.value.forEach(column > {if (!column.children) {fitstTitleL…...

【算法训练营Day07】字符串part1

文章目录 反转字符串反转字符串II替换数字 反转字符串 题目链接&#xff1a;344. 反转字符串 双指针法&#xff0c;两个指针的元素直接调转即可 class Solution {public void reverseString(char[] s) {int head 0;int end s.length - 1;while(head < end) {char temp …...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...

安全突围:重塑内生安全体系:齐向东在2025年BCS大会的演讲

文章目录 前言第一部分&#xff1a;体系力量是突围之钥第一重困境是体系思想落地不畅。第二重困境是大小体系融合瓶颈。第三重困境是“小体系”运营梗阻。 第二部分&#xff1a;体系矛盾是突围之障一是数据孤岛的障碍。二是投入不足的障碍。三是新旧兼容难的障碍。 第三部分&am…...

c++第七天 继承与派生2

这一篇文章主要内容是 派生类构造函数与析构函数 在派生类中重写基类成员 以及多继承 第一部分&#xff1a;派生类构造函数与析构函数 当创建一个派生类对象时&#xff0c;基类成员是如何初始化的&#xff1f; 1.当派生类对象创建的时候&#xff0c;基类成员的初始化顺序 …...

tomcat入门

1 tomcat 是什么 apache开发的web服务器可以为java web程序提供运行环境tomcat是一款高效&#xff0c;稳定&#xff0c;易于使用的web服务器tomcathttp服务器Servlet服务器 2 tomcat 目录介绍 -bin #存放tomcat的脚本 -conf #存放tomcat的配置文件 ---catalina.policy #to…...

Spring Security 认证流程——补充

一、认证流程概述 Spring Security 的认证流程基于 过滤器链&#xff08;Filter Chain&#xff09;&#xff0c;核心组件包括 UsernamePasswordAuthenticationFilter、AuthenticationManager、UserDetailsService 等。整个流程可分为以下步骤&#xff1a; 用户提交登录请求拦…...

高分辨率图像合成归一化流扩展

大家读完觉得有帮助记得关注和点赞&#xff01;&#xff01;&#xff01; 1 摘要 我们提出了STARFlow&#xff0c;一种基于归一化流的可扩展生成模型&#xff0c;它在高分辨率图像合成方面取得了强大的性能。STARFlow的主要构建块是Transformer自回归流&#xff08;TARFlow&am…...

用 Rust 重写 Linux 内核模块实战:迈向安全内核的新篇章

用 Rust 重写 Linux 内核模块实战&#xff1a;迈向安全内核的新篇章 ​​摘要&#xff1a;​​ 操作系统内核的安全性、稳定性至关重要。传统 Linux 内核模块开发长期依赖于 C 语言&#xff0c;受限于 C 语言本身的内存安全和并发安全问题&#xff0c;开发复杂模块极易引入难以…...