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

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

詳解Springboot下載Excel的三種方式

瀏覽:157日期: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
相關文章:
主站蜘蛛池模板: 道康宁消泡剂-瓦克-大川进口消泡剂供应商 | 安平县鑫川金属丝网制品有限公司,防风抑尘网,单峰防风抑尘,不锈钢防风抑尘网,铝板防风抑尘网,镀铝锌防风抑尘网 | 广州番禺搬家公司_天河黄埔搬家公司_企业工厂搬迁_日式搬家_广州搬家公司_厚道搬迁搬家公司 | 胶水,胶粘剂,AB胶,环氧胶,UV胶水,高温胶,快干胶,密封胶,结构胶,电子胶,厌氧胶,高温胶水,电子胶水-东莞聚力-聚厉胶粘 | 沟盖板_复合沟盖板厂_电力盖板_树脂雨水篦子-淄博拜斯特 | 浙江上沪阀门有限公司| 进口试验机价格-进口生物材料试验机-西安卡夫曼测控技术有限公司 | 东莞注册公司-代办营业执照-东莞公司注册代理记账-极刻财税 | 蓝米云-专注于高性价比香港/美国VPS云服务器及海外公益型免费虚拟主机 | 开锐教育-学历提升-职称评定-职业资格培训-积分入户 | 冷轧机|两肋冷轧机|扁钢冷轧机|倒立式拉丝机|钢筋拔丝机|收线机-巩义市华瑞重工机械制造有限公司 | 蓝莓施肥机,智能施肥机,自动施肥机,水肥一体化项目,水肥一体机厂家,小型施肥机,圣大节水,滴灌施工方案,山东圣大节水科技有限公司官网17864474793 | 筛分机|振动筛分机|气流筛分机|筛分机厂家-新乡市大汉振动机械有限公司 | 济宁工业提升门|济宁电动防火门|济宁快速堆积门-济宁市统一电动门有限公司 | 上海冠顶工业设备有限公司-隧道炉,烘箱,UV固化机,涂装设备,高温炉,工业机器人生产厂家 | 上海办公室装修,写字楼装修—启鸣装饰设计工程有限公司 | 气弹簧定制-气动杆-可控气弹簧-不锈钢阻尼器-工业气弹簧-可调节气弹簧厂家-常州巨腾气弹簧供应商 | 酒店厨房设计_中央厨房设计_北京商用厨房设计公司-奇能商厨 | 水冷式工业冷水机组_风冷式工业冷水机_水冷螺杆冷冻机组-深圳市普威机械设备有限公司 | 创客匠人-让IP变现不走弯路 | 干式磁选机_湿式磁选机_粉体除铁器-潍坊国铭矿山设备有限公司 | 通用磨耗试验机-QUV耐候试验机|久宏实业百科 | 讲师宝经纪-专业培训机构师资供应商_培训机构找讲师、培训师、讲师经纪就上讲师宝经纪 | 聚氨酯催化剂K15,延迟催化剂SA-1,叔胺延迟催化剂,DBU,二甲基哌嗪,催化剂TMR-2,-聚氨酯催化剂生产厂家 | 北京西风东韵品牌与包装设计公司,创造视觉销售力! | 成都办公室装修-办公室设计-写字楼装修设计-厂房装修-四川和信建筑装饰工程有限公司 | 阳光模拟试验箱_高低温试验箱_高低温冲击试验箱_快速温变试验箱|东莞市赛思检测设备有限公司 | 湖南档案密集架,智能,物证,移动,价格-湖南档案密集架厂家 | 质检报告_CE认证_FCC认证_SRRC认证_PSE认证_第三方检测机构-深圳市环测威检测技术有限公司 | 高精度电阻回路测试仪-回路直流电阻测试仪-武汉特高压电力科技有限公司 | 南京精锋制刀有限公司-纵剪机刀片_滚剪机刀片_合金刀片厂家 | 山东活动策划|济南活动公司|济南公关活动策划-济南锐嘉广告有限公司 | 锡膏喷印机-全自动涂覆机厂家-全自动点胶机-视觉点胶机-深圳市博明智控科技有限公司 | 广州工业氧气-工业氩气-工业氮气-二氧化碳-广州市番禺区得力气体经营部 | 对夹式止回阀_对夹式蝶形止回阀_对夹式软密封止回阀_超薄型止回阀_不锈钢底阀-温州上炬阀门科技有限公司 | ALC墙板_ALC轻质隔墙板_隔音防火墙板_轻质隔墙材料-湖北博悦佳 | 重庆磨床过滤机,重庆纸带过滤机,机床伸缩钣金,重庆机床钣金护罩-重庆达鸿兴精密机械制造有限公司 | 物流之家新闻网-最新物流新闻|物流资讯|物流政策|物流网-匡匡奈斯物流科技 | 【直乐】河北石家庄脊柱侧弯医院_治疗椎间盘突出哪家医院好_骨科脊柱外科专业医院_治疗抽动症/关节病骨伤权威医院|排行-直乐矫形中医医院 | 电缆接头-防爆电缆接头-格兰头-金属电缆接头-防爆填料函 | 废旧物资回收公司_广州废旧设备回收_报废设备物资回收-益美工厂设备回收公司 |