前端vue后端java使用easyexcel框架下載表格xls數據工具類

?一 使用alibaba開源的 easyexcel框架,后臺只需一個工具類即可實現下載

后端下載實現

? 依賴 pom.xml
 <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.0</version></dependency>
后臺JAVA代碼
/*** 下載xls數據* @param params* @param response* @throws IOException*/@PostMapping("/exportData")public void exportData(@RequestBody String params, HttpServletResponse response) throws IOException {JSONObject query = JSONObject.parseObject(params);String beginTime = query.getString("beginDate");String endTime = query.getString("endDate");List<AliIotLog> resultList = new ArrayList<>();//查詢業務數據列表  resultList WebDownloadUtil.downloadXlsByList(response, resultList,LogExport.class,"xls");}

一個 java bean代碼,用于設置導出時的列映射顯示名稱關系

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import java.io.Serializable;
import java.time.LocalDateTime;@ContentRowHeight(20)//注解用于指定某元素的內容行高度為20。
@HeadRowHeight(20)//注解用于指定某元素的表頭行高度為20。
@ColumnWidth(30) //注解用于指定某元素的列寬度為30。
public class LogExport implements Serializable {private static final long serialVersionUID = 1L;/*** 設備協議內容*/@ExcelProperty("接收報文")private String inHexStr;/*** 回復內容*/@ExcelProperty("發送報文")private String outHexStr;/*** 地址或通道*/@ExcelProperty("地址")private String addr;/*** 時間*/@ExcelProperty("時間")private LocalDateTime ctime;public String getInHexStr() {return inHexStr;}public void setInHexStr(String inHexStr) {this.inHexStr = inHexStr;}public String getOutHexStr() {return outHexStr;}public void setOutHexStr(String outHexStr) {this.outHexStr = outHexStr;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}public LocalDateTime getCtime() {return ctime;}public void setCtime(LocalDateTime ctime) {this.ctime = ctime;}}

?完整下載工具類代碼
/*** web 下載文件封裝* @author hua* @date 2024-07-06 14:30*/
public class WebDownloadUtil {/*** 下載文件* @param response* @param resultList 列表數據* @param clazz 類形* @param format 表格格式 xlx xlsx csv* @throws IOException*/public static void downloadXlsByList(HttpServletResponse response, List resultList,Class clazz,String format) throws IOException {response.setContentType("application/vnd.ms-excel");response.setHeader("content-disposition","attachment;filename=data_export.xls");//下載文件名稱在前端vue頁面處理ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.CSV;if("xls".equals(format)){excelTypeEnum = ExcelTypeEnum.XLS;}else if("xlsx".equals(format)){excelTypeEnum = ExcelTypeEnum.XLSX;}ExcelWriterBuilder writeWork = EasyExcel.write(response.getOutputStream(),clazz  ).excelType(excelTypeEnum).registerConverter(new Converter<LocalDateTime>(){public String format = "yyyy-MM-dd HH:mm:ss";@Overridepublic Class<LocalDateTime> supportJavaTypeKey() {return LocalDateTime.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.STRING;}@Overridepublic LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(format)).atStartOfDay();}@Overridepublic WriteCellData<?> convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {if(localDateTime==null){return new WriteCellData<>("");}DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);String format = formatter.format(localDateTime);return new WriteCellData(format);}});ExcelWriterSheetBuilder sheet = writeWork.sheet();sheet.doWrite(resultList);}
}

前端vue下載實現

vue前端頁下載調用按鈕
   import webUtil from "@api/webUtil";export default {name: 'sys_log',data () {return {queryBody:{},list:[],
}methods: {exportExcel () {//單擊下載console.log('query data',this.queryBody)let url='/xxx/xxx/xxxx';webUtil.downloadXls(url,this.queryBody,"導出數據")}}}
vue 完整下載工具類
import request from '@/plugins/request';const webUtil= {downloadXls:function(url,data, fileNamePrefix){request({url: url,method: 'post',responseType: "blob",data}).then(data => {let blob = new Blob([data], {type: 'application/x-msdownload;charset=UTF-8'});let fileName = fileNamePrefix + Date.parse(new Date()) + '.xls';if (window.navigator.msSaveOrOpenBlob) {navigator.msSaveBlob(blob, fileName);} else {let link = document.createElement('a');link.href = window.URL.createObjectURL(blob);link.download = fileName;link.click();window.URL.revokeObjectURL(link.href);}}).catch(error => {console.error('Error exporting and downloading data:', error);}));}};
export default webUtil;
最終下載效果。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/42043.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/42043.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/42043.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

MATLAB-分類CPO-RF-Adaboost冠豪豬優化器(CPO)優化RF隨機森林結合Adaboost分類預測(二分類及多分類)

MATLAB-分類CPO-RF-Adaboost冠豪豬優化器&#xff08;CPO&#xff09;優化RF隨機森林結合Adaboost分類預測&#xff08;二分類及多分類&#xff09; 分類CPO-RF-Adaboost冠豪豬優化器&#xff08;CPO&#xff09;優化RF隨機森林結合Adaboost分類預測&#xff08;二分類及多分類…

docker 設置代理,通過代理服務器拉取鏡像

docker 拉取目標鏡像需要通過代理服務器進行時&#xff0c;可以通過為 docker 配置全局代理來實現。 注&#xff1a;Linux 上通過臨時命令 export HTTP_PROXY 設置的代理&#xff0c;對 curl 這些有用&#xff0c;但是對 docker pull 不起作用。 示例 假設您的代理服務器地址是…

Nginx目錄文件作用

查看文件 [rootlocalhost nginx]# pwd /opt/nginx [rootlocalhost nginx]# ll total 4 drwx------ 2 nobody root 6 Jun 6 09:11 client_body_temp drwxr-xr-x 3 root root 4096 Feb 28 14:30 conf drwx------ 2 nobody root 6 Feb 28 14:29 fastcgi_temp drwxr-xr-x…

【web前端HTML+CSS+JS】--- HTML學習筆記01

學習鏈接&#xff1a;黑馬程序員pink老師前端入門教程&#xff0c;零基礎必看的h5(html5)css3移動端前端視頻教程_嗶哩嗶哩_bilibili 學習文檔&#xff1a; Web 開發技術 | MDN (mozilla.org) 一、前后端工作流程 WEB模型&#xff1a;前端用于采集和展示信息&#xff0c;中…

Web漏洞掃描工具AppScan與AWVS測評及使用體驗

AppScan和AWVS業界知名的Web漏洞掃描工具&#xff0c;你是否也好奇到底哪一個能力更勝一籌呢&#xff1f;接下來跟隨博主一探究竟吧。 1. 方案概覽 第一步&#xff1a;安裝一個用于評測的Web漏洞靶場&#xff08;本文采用最知名和最廣泛使用的靶場&#xff0c;即OWASP Benchma…

啥?你沒聽過SpringBoot的FatJar?

寫在最前面&#xff1a; SpringBoot是目前企業里最流行的框架之一&#xff0c;SpringBoot的部署方式多數采用jar包形式。通常&#xff0c;我們使用java -jar便可以直接運行jar文件。普通的jar只包含當前 jar的信息&#xff0c;當內部依賴第三方jar時&#xff0c;直接運行則會報…

robotframework-appiumLibrary 應用 - 實現 app 自動化

1、安裝appiumLibrary第三方庫 運行pip命令&#xff1a;pip install robotframework-appiumlibrary 若已安裝&#xff0c;需要更新版本可以用命令&#xff1a;pip install -U robotframework-appiumlibrary 2、安裝app自動化環境。 參考我的另外一篇專門app自動化環境安裝的…

設計模式探索:策略模式

1. 什么是策略模式&#xff08;Strategy Pattern&#xff09; 定義 策略模式&#xff08;Strategy Pattern&#xff09;的原始定義是&#xff1a;定義一系列算法&#xff0c;將每一個算法封裝起來&#xff0c;并使它們可以相互替換。策略模式讓算法可以獨立于使用它的客戶端而…

打卡第4天----鏈表

通過學習基礎,發現我的基本功還得需要再練練,思路得再更加清晰明了,這樣子做算法題才能駕輕就熟。每天記錄自己的進步。 一、兩兩交換 題目編號:24 題目描述: 給你一個鏈表,兩兩交換其中相鄰的節點,并返回交換后鏈表的頭節點。你必須在不修改節點內部的值的情況下完成本…

[數據結構] 基于交換的排序 冒泡排序快速排序

標題&#xff1a;[數據結構] 基于交換的排序 冒泡排序&&快速排序 水墨不寫bug &#xff08;圖片來源于網絡&#xff09; 目錄 &#xff08;一&#xff09;冒泡排序 優化后實現&#xff1a; &#xff08;二&#xff09;快速排序 I、實現方法&#xff1a; &#…

opencv環境搭建-python

最近遇到了一些圖像處理的需求&#xff0c;所以需要學習一下opencv,來記錄一下我的學習歷程。 安裝numpy pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy安裝matplotlib pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib安裝opencv …

ctfshow web入門 web338--web344

web338 原型鏈污染 comman.js module.exports {copy:copy };function copy(object1, object2){for (let key in object2) {if (key in object2 && key in object1) {copy(object1[key], object2[key])} else {object1[key] object2[key]}}}login.js var express …

【ubuntu】掛載新磁盤

1、查看磁盤 sudo fdisk -l#Disk /dev/sdb: 4.0 TiB #Disk model: HNA641010BCF105 #Units: sectors of 1 * 512 512 bytes #Sector size (logical/physical): 512 bytes / 4096 bytes #I/O size (minimum/optimal): 4096 bytes / 4096 bytes #Disklabel type: gpt #Disk id…

python argparse模塊nargs用法

nargs 是 argparse 模塊中用來指定參數的數量的屬性。不同的 nargs 取值有不同的含義&#xff0c;下面是一些常用的用法&#xff1a; nargsNone (默認值)&#xff1a;表示該參數只能接收一個值。例如&#xff1a;--foo 123。 nargs?&#xff1a;表示該參數最多接收一個值。如…

gcc/g++的四步編譯

目錄 前言1.預處理&#xff08;進行宏替換&#xff09;2.編譯&#xff08;生成匯編&#xff09;3.匯編&#xff08;生成二進制文件&#xff09;4. 鏈接 &#xff08;生成可執行文件&#xff09;a. 動態庫 && 動態鏈接b. 靜態庫 && 靜態鏈接c. 驗證d. 動靜態鏈接…

技術實現路徑怎么寫?(Word項目技術路徑文檔參考)

軟件項目編寫技術實現路徑至關重要&#xff0c;因為它為項目團隊提供了清晰的開發藍圖。這一路徑明確了從項目啟動到交付各階段所需的技術方案、步驟及預期成果&#xff0c;有助于團隊統一認識&#xff0c;確保開發工作有序進行。同時&#xff0c;技術實現路徑有助于識別潛在的…

HetuEngine簡介

目錄 HetuEngine是什么&#xff1f; HetuEngine的特點以及使用場景 特點 使用場景 HetuEngine介紹 結構 近期用到了Hetu&#xff0c;了解下這個工具是起什么作用的。 HetuEngine是什么&#xff1f; 是引擎&#xff0c;設計是為了讓與當前的大數據生態完美融合的引擎&am…

本安防爆手機:危險環境下的安全通信解決方案

在石油化工、煤礦、天然氣等危險環境中&#xff0c;通信安全是保障工作人員生命安全和生產順利進行的關鍵。防爆智能手機作為專為這些環境設計的通信工具&#xff0c;提供了全方位的安全通信解決方案。 防爆設計與材料&#xff1a; 防爆智能手機采用特殊的防爆結構和材料&…

Mysql部署MHA高可用

部署前準備&#xff1a; mysql-8.0.27下載地址&#xff1a;https://cdn.mysql.com//Downloads/MySQL-8.0/mysql-8.0.27-1.el7.x86_64.rpm-bundle.tar mha-manager下載地址&#xff1a;https://github.com/yoshinorim/mha4mysql-manager/releases/download/v0.58/mha4mysql-mana…

【Selenium】 使用save_screenshot截圖無法保存圖片

Selenium 使用save_screenshot截圖無法保存 代碼如下 from time import sleep from selenium import webdriver driver webdriver.Chrome() driver.maximize_window() driver.get(http://www.baidu.com) # 截取當前窗口&#xff0c;指定截圖圖片的保存位置 driver.save_scre…