电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

詳解Springboot下載Excel的三種方式

瀏覽:158日期:2022-06-15 16:12:36

匯總一下瀏覽器下載和代碼本地下載實現的3種方式。

(其實一般都是在代碼生成excel,然后上傳到oss,然后傳鏈接給前臺,但是我好像沒有實現過直接點擊就能在瀏覽器下載的功能,所以這次一起匯總一下3種實現方式。)

🔥1.EasyExcel--瀏覽器下載1.Maven環境

​網絡上有很多maven的easyexcel版本,還是推薦alibaba的easyexcel,操作簡單,代碼不冗余

<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel --><dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.10</version></dependency>

2.完整代碼實現

控制層:設置response格式然后直接下載即可

package com.empirefree.springboot.controller;import com.alibaba.excel.EasyExcel;import com.empirefree.springboot.pojo.User;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;/** * @program: springboot * @description: * @author: huyuqiao * @create: 2021/07/04 15:01 */@RestControllerpublic class UserController { /** * Author: HuYuQiao * Description: 瀏覽器下載--excel */ @GetMapping('/testRespExcel') public void testRespExcel(HttpServletResponse response){response.addHeader('Content-Disposition', 'attachment;filename=' + 'huyuqiao.xlsx');response.setContentType('application/vnd.ms-excel;charset=gb2312');try {// 從HttpServletResponse中獲取OutputStream輸出流 ServletOutputStream outputStream = response.getOutputStream(); /* * EasyExcel 有多個不同的read方法,適用于多種需求 * 這里調用EasyExcel中通過OutputStream流方式輸出Excel的write方法 * 它會返回一個ExcelWriterBuilder類型的返回值 * ExcelWriterBuilde中有一個doWrite方法,會輸出數據到設置的Sheet中 */ EasyExcel.write(outputStream, User.class).sheet('測試數據').doWrite(getAllUser());} catch (IOException e) { e.printStackTrace();} } public List<User> getAllUser(){List<User> userList = new ArrayList<>();for (int i=0;i<100;i++){ User user = User.builder().name('胡宇喬'+ i).password('huyuqiao').age(i).build(); userList.add(user);}return userList; }}

實體類:給User設置對應的excel屬性即可,value代表excel中名字,index代表第幾列

package com.empirefree.springboot.pojo;import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.metadata.BaseRowModel;import lombok.Builder;import lombok.Data;/** * @program: springboot * @description: user * @author: huyuqiao * @create: 2021/07/04 14:53 */@Data@Builderpublic class User extends BaseRowModel{ @ExcelProperty(value = '姓名',index = 0) private String name; @ExcelProperty(value = '密碼',index = 1) private String password; @ExcelProperty(value = '年齡',index = 2) private Integer age;}3.實現效果

詳解Springboot下載Excel的三種方式

🔥2.EasyExcel--本地下載1.完整代碼實現

​maven和上面一樣,只是文件輸出流設置一下即可

package com.empirefree.springboot.controller;import com.alibaba.excel.EasyExcel;import com.empirefree.springboot.pojo.User;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;/** * @program: springboot * @description: * @author: huyuqiao * @create: 2021/07/04 15:01 */@RestControllerpublic class UserController { /** * Author: HuYuQiao * Description:本地生成--excel */ @GetMapping('/testLocalExcel') public void testLocalExcel(){// 文件輸出位置OutputStream out = null;try { out = new FileOutputStream('C:UsersEDYDesktopempirefree.xlsx'); EasyExcel.write(out, User.class).sheet('測試數據').doWrite(getAllUser());} catch (FileNotFoundException e) { e.printStackTrace();}finally { try {// 關閉流out.close(); } catch (IOException e) {e.printStackTrace(); }} } public List<User> getAllUser(){List<User> userList = new ArrayList<>();for (int i=0;i<100;i++){ User user = User.builder().name('張三'+ i).password('1234').age(i).build(); userList.add(user);}return userList; }}2.實現效果

詳解Springboot下載Excel的三種方式

🔥3.Poi--瀏覽器實現下載1.Maven環境

<!-- excel導出工具 --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>RELEASE</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>RELEASE</version></dependency>2.代碼實現

控制層

/** * Author: HuYuQiao * Description: excle-export */ @GetMapping('/export') public String exportExcel(HttpServletResponse response) {System.out.println('成功到達到處excel....');String fileName = 'test.xls';if (fileName == null || ''.equals(fileName)) { return '文件名不能為空!';} else { if (fileName.endsWith('xls')) {Boolean isOk = excelService.exportExcel(response, fileName, 1, 10);if (isOk) { return '導出成功!';} else { return '導出失敗!';} } return '文件格式有誤!';} }

serviceimpl層

/** * Author: HuYuQiao * Description: excel-impl */ @Override public Boolean exportExcel(HttpServletResponse response, String fileName, Integer pageNum, Integer pageSize) {log.info('導出數據開始。。。。。。');//查詢數據并賦值給ExcelDataList<User> userList = userMapper.find();System.out.println(userList.size() + 'size');List<String[]> list = new ArrayList<String[]>();for (User user : userList) { String[] arrs = new String[4]; arrs[0] = String.valueOf(user.getId()); arrs[1] = user.getUsername(); arrs[2] = user.getPassword(); arrs[3] = String.valueOf(user.getEnable()); list.add(arrs);}//表頭賦值String[] head = {'序列', '用戶名', '密碼', '狀態'};ExcelData data = new ExcelData();data.setHead(head);data.setData(list);data.setFileName(fileName);//實現導出try { ExcelUtil.exportExcel(response, data); log.info('導出數據結束。。。。。。'); return true;} catch (Exception e) { log.info('導出數據失敗。。。。。。'); return false;} }

工具類

package com.example.demo.utils;import com.example.demo.entity.ExcelData;import com.example.demo.entity.User;import lombok.extern.slf4j.Slf4j;import org.apache.poi.hssf.usermodel.*;import org.apache.poi.ss.usermodel.*;import javax.servlet.http.HttpServletResponse;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import static org.apache.poi.ss.usermodel.CellType.*;/** * Author: HuYuQiao * Description: excelUtil */@Slf4jpublic class ExcelUtil { /** * Author: HuYuQiao * Description: excelUtil-export */ public static void exportExcel(HttpServletResponse response, ExcelData data) {log.info('導出解析開始,fileName:{}',data.getFileName());try { //實例化HSSFWorkbook HSSFWorkbook workbook = new HSSFWorkbook(); //創建一個Excel表單,參數為sheet的名字 HSSFSheet sheet = workbook.createSheet('sheet'); //設置表頭 setTitle(workbook, sheet, data.getHead()); //設置單元格并賦值 setData(sheet, data.getData()); //設置瀏覽器下載 setBrowser(response, workbook, data.getFileName()); log.info('導出解析成功!');} catch (Exception e) { log.info('導出解析失敗!'); e.printStackTrace();} } /** * Author: HuYuQiao * Description: excelUtil-settitle */ private static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {try { HSSFRow row = sheet.createRow(0); //設置列寬,setColumnWidth的第二個參數要乘以256,這個參數的單位是1/256個字符寬度 for (int i = 0; i <= str.length; i++) {sheet.setColumnWidth(i, 15 * 256); } //設置為居中加粗,格式化時間格式 HSSFCellStyle style = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); font.setBold(true); style.setFont(font); style.setDataFormat(HSSFDataFormat.getBuiltinFormat('m/d/yy h:mm')); //創建表頭名稱 HSSFCell cell; for (int j = 0; j < str.length; j++) {cell = row.createCell(j);cell.setCellValue(str[j]);cell.setCellStyle(style); }} catch (Exception e) { log.info('導出時設置表頭失敗!'); e.printStackTrace();} } /** * Author: HuYuQiao * Description: excelUtil-setData */ private static void setData(HSSFSheet sheet, List<String[]> data) {try{ int rowNum = 1; for (int i = 0; i < data.size(); i++) {HSSFRow row = sheet.createRow(rowNum);for (int j = 0; j < data.get(i).length; j++) { row.createCell(j).setCellValue(data.get(i)[j]);}rowNum++; } log.info('表格賦值成功!');}catch (Exception e){ log.info('表格賦值失敗!'); e.printStackTrace();} } /** * Author: HuYuQiao * Description: excelUtil-setBrowser */ private static void setBrowser(HttpServletResponse response, HSSFWorkbook workbook, String fileName) {try { //清空response response.reset(); //設置response的Header response.addHeader('Content-Disposition', 'attachment;filename=' + fileName); OutputStream os = new BufferedOutputStream(response.getOutputStream()); response.setContentType('application/vnd.ms-excel;charset=gb2312'); //將excel寫入到輸出流中 workbook.write(os); os.flush(); os.close(); log.info('設置瀏覽器下載成功!');} catch (Exception e) { log.info('設置瀏覽器下載失敗!'); e.printStackTrace();} } /** * Author: HuYuQiao * Description: excelUtil--importExcel */ public static List<Object[]> importExcel(String fileName) {log.info('導入解析開始,fileName:{}',fileName);try { List<Object[]> list = new ArrayList<>(); InputStream inputStream = new FileInputStream(fileName); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); //獲取sheet的行數 int rows = sheet.getPhysicalNumberOfRows(); for (int i = 0; i < rows; i++) {//過濾表頭行if (i == 0) { continue;}//獲取當前行的數據Row row = sheet.getRow(i);Object[] objects = new Object[row.getPhysicalNumberOfCells()];int index = 0;for (Cell cell : row) { if (cell.getCellType().equals(NUMERIC)) {objects[index] = (int) cell.getNumericCellValue(); } if (cell.getCellType().equals(STRING)) {objects[index] = cell.getStringCellValue(); } if (cell.getCellType().equals(BOOLEAN)) {objects[index] = cell.getBooleanCellValue(); } if (cell.getCellType().equals(ERROR)) {objects[index] = cell.getErrorCellValue(); } index++;}list.add(objects); } log.info('導入文件解析成功!'); return list;}catch (Exception e){ log.info('導入文件解析失敗!'); e.printStackTrace();}return null; } //測試導入 public static void main(String[] args) {try { String fileName = 'E:/test.xlsx'; List<Object[]> list = importExcel(fileName); for (int i = 0; i < list.size(); i++) {User user = new User();user.setId((Integer) list.get(i)[0]);user.setUsername((String) list.get(i)[1]);user.setPassword((String) list.get(i)[2]);user.setEnable((Integer) list.get(i)[3]);System.out.println(user.toString()); }} catch (Exception e) { e.printStackTrace();} }}3.實現效果

詳解Springboot下載Excel的三種方式

🔥4.總結

總體看來:當excel需要在瀏覽器下載時,使用alibaba的easyexcel最快最方便,并且注意需要設置response格式

到此這篇關于詳解Springboot下載Excel的三種方式的文章就介紹到這了,更多相關Springboot下載Excel內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: excel
相關文章:
主站蜘蛛池模板: 锤式粉碎机,医药粉碎机,锥式粉碎机-无锡市迪麦森机械制造有限公司 | 耐酸碱胶管_耐腐蚀软管总成_化学品输送软管_漯河利通液压科技耐油耐磨喷砂软管|耐腐蚀化学软管 | 冷镦机-多工位冷镦机-高速冷镦机厂家-温州金诺机械设备制造有限公司 | 北京网络营销推广_百度SEO搜索引擎优化公司_网站排名优化_谷歌SEO - 北京卓立海创信息技术有限公司 | 网站建设-网站制作-网站设计-网站开发定制公司-网站SEO优化推广-咏熠软件 | 下水道疏通_管道疏通_马桶疏通_附近疏通电话- 立刻通 | 郑州巴特熔体泵有限公司专业的熔体泵,熔体齿轮泵与换网器生产厂家 | 洁净化验室净化工程_成都实验室装修设计施工_四川华锐净化公司 | 包装盒厂家_纸盒印刷_礼品盒定制-济南恒印包装有限公司 | 赛默飞Thermo veritiproPCR仪|ProFlex3 x 32PCR系统|Countess3细胞计数仪|371|3111二氧化碳培养箱|Mirco17R|Mirco21R离心机|仟诺生物 | 通风天窗,通风气楼,屋顶通风天窗,屋顶通风天窗公司 | 乳化沥青设备_改性沥青设备_沥青加温罐_德州市昊通路桥工程有限公司 | 十字轴_十字轴万向节_十字轴总成-南京万传机械有限公司 | 深圳市源和塑胶电子有限公司-首页 | 路斯特伺服驱动器维修,伦茨伺服驱动器维修|万骏自动化百科 | Honsberg流量计-Greisinger真空表-气压计-上海欧臻机电设备有限公司 | 质检报告_CE认证_FCC认证_SRRC认证_PSE认证_第三方检测机构-深圳市环测威检测技术有限公司 | sus630/303cu不锈钢棒,440C/430F/17-4ph不锈钢研磨棒-江苏德镍金属科技有限公司 | 中图网(原中国图书网):网上书店,尾货特色书店,30万种特价书低至2折! | 美国查特CHART MVE液氮罐_查特杜瓦瓶_制造全球品质液氮罐 | 登车桥动力单元-非标液压泵站-非标液压系统-深圳市三好科技有限公司 | 膜结构_ETFE膜结构_膜结构厂家_膜结构设计-深圳市烨兴智能空间技术有限公司 | 钢格板|镀锌钢格板|热镀锌钢格板|格栅板|钢格板|钢格栅板|热浸锌钢格板|平台钢格板|镀锌钢格栅板|热镀锌钢格栅板|平台钢格栅板|不锈钢钢格栅板 - 专业钢格板厂家 | 中天寰创-内蒙古钢结构厂家|门式刚架|钢结构桁架|钢结构框架|包头钢结构煤棚 | 波纹补偿器_不锈钢波纹补偿器_巩义市润达管道设备制造有限公司 | 立式壁挂广告机厂家-红外电容触摸一体机价格-华邦瀛 | 超声波清洗机_超声波清洗机设备_超声波清洗机厂家_鼎泰恒胜 | 防水套管-柔性防水套管-刚性防水套管-上海执品管件有限公司 | 气密性检测仪_气密性检测设备_防水测试仪_密封测试仪-岳信仪器 | 山东艾德实业有限公司| 铝扣板-铝方通-铝格栅-铝条扣板-铝单板幕墙-佳得利吊顶天花厂家 elisa试剂盒价格-酶联免疫试剂盒-猪elisa试剂盒-上海恒远生物科技有限公司 | 铝箔袋,铝箔袋厂家,东莞铝箔袋,防静电铝箔袋,防静电屏蔽袋,防静电真空袋,真空袋-东莞铭晋让您的产品与众不同 | 便携式表面粗糙度仪-彩屏硬度计-分体式粗糙度仪-北京凯达科仪科技有限公司 | 根系分析仪,大米外观品质检测仪,考种仪,藻类鉴定计数仪,叶面积仪,菌落计数仪,抑菌圈测量仪,抗生素效价测定仪,植物表型仪,冠层分析仪-杭州万深检测仪器网 | 旋振筛|圆形摇摆筛|直线振动筛|滚筒筛|压榨机|河南天众机械设备有限公司 | 学叉车培训|叉车证报名|叉车查询|叉车证怎么考-工程机械培训网 | 蜜蜂职场文库_职场求职面试实用的范文资料大全 | 好物生环保网、环保论坛 - 环保人的学习交流平台| DNA亲子鉴定_DNA基因检测中心官方预约平台-严选好基因网 | 自动检重秤-动态称重机-重量分选秤-苏州金钻称重设备系统开发有限公司 | 网站seo优化_seo云优化_搜索引擎seo_启新网络服务中心 |