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

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

SpringBoot內存數據導出成Excel的實現方法

瀏覽:144日期:2022-06-16 14:04:55
前言

這是本人寫的一個SpringBoot對Excel寫入的方法,實測能用,待提升的地方有很多,有不足之處請多多指點。

Excel2003版(后綴為.xls)最大行數是65536行,最大列數是256列。

Excel2007以上的版本(后綴為.xlsx)最大行數是1048576行,最大列數是16384列。

若數據量超出行數,需要進行腳頁的控制,這一點沒做,因為一般100W行已夠用。

提供3種方法寫入:

1.根據給定的實體類列List和列名數組arr[]進行Excel寫入

2.根據給定的List和key的順序數組key[]進行Excel寫入

3.根據給定的List按順序Excel寫入,列名數組arr[]需要自行和數據列順序進行一一對應

同名的Excel會被覆蓋!!!

寫入Excel所需要的幾個類

SpringBoot內存數據導出成Excel的實現方法

1.在pom.xml加上依賴

</dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency></dependencies>2.ExcelPOJO實體類

package com.cly.utils.Excel;/** * @author : CLy * @ClassName : ExcelPOJO * @date : 2020/7/9 17:13 * 實體類所有成員變量都需要有GET,SET方法 * 所有成員變量都要加上注解@excelRescoure(value = '?'),?為Excel真實列名,必須一一對應 * @excelRescoure(value = '?'),?可為空,需要用到才賦值 * 成員變量目前只允許String,Double,Interge,Float **/public class ExcelPOJO { public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPasswork() { return passwork; } public void setPasswork(String passwork) { this.passwork = passwork; } public String getLook() { return look; } public void setLook(String look) { this.look = look; } @excelRescoure(value = '姓名') private String name; @excelRescoure(value = '密碼') private String passwork; @excelRescoure(value = '工號') private String look; @Override public String toString(){ return 'name:'+this.getName()+',passwork:'+this.getPasswork()+',look:'+this.getLook(); } public ExcelPOJO() {}}3.@interface自定義注解(用于實體類讀取)

package com.cly.utils.Excel;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author : CLy * @ClassName : myRescoure * @date : 2020/7/10 9:31 **/@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface excelRescoure { String value() default '';//默認為空}4.excelWrite類(寫入Excel數據類)有很多冗余的代碼,可抽離出來

package com.cly.utils.Excel;import org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.XSSFCellStyle;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletResponse;import java.beans.IntrospectionException;import java.beans.PropertyDescriptor;import java.io.*;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.net.URLEncoder;import java.text.SimpleDateFormat;import java.util.*;/** * @author : CLy * @ClassName : excelWrite * @date : 2020/7/17 17:01 **/public class excelWrite { //日志輸出 private static Logger logger = LoggerFactory.getLogger(excelWrite.class); /** * 方法一: * 實體類數據寫入新建的excel * @path:excel文件路徑 * @array[]:文件首行數據列名,可為空,為空時不存在首行列名 * @list<T>:實體類數據數列 */ public static <T> String writeToExcelByPOJO(String path, String[] array, List<T> list) { /* for (T t : list) { System.out.println(t); }*/ //創建工作薄 Workbook wb = new XSSFWorkbook(); /**標題和頁碼*/ CellStyle titleStyle = wb.createCellStyle(); // 設置單元格對齊方式 titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 //titleStyle.setVerticalAlignment(); // 默認垂直居中 // 設置字體樣式 Font titleFont = wb.createFont(); titleFont.setFontHeightInPoints((short) 12); // 字體高度 titleFont.setFontName('黑體'); // 字體樣式 titleStyle.setFont(titleFont); //創建sheet Sheet sheet = wb.createSheet('第一頁'); sheet.autoSizeColumn(0);// 自動設置寬度 // 在sheet中添加標題行 Row row = sheet.createRow((int) 0);// 行數從0開始 for (int i = 0; i < array.length; i++) { Cell cell = row.createCell(i); cell.setCellValue(array[i]); cell.setCellStyle(titleStyle); } /**數據樣式*/ // 數據樣式 因為標題和數據樣式不同 需要分開設置 不然會覆蓋 CellStyle dataStyle = wb.createCellStyle(); // 設置居中樣式 dataStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 /**處理實體類數據并寫入*/ //獲取當前的泛型對象 Object obj = list.get(0); ArrayList arrayList = new ArrayList(); //LinkedHashMap保證順序 LinkedHashMap<String, Object> POJOfields = getPOJOFieldAndValue(obj); for (int i = 0; i < array.length; i++) { for (Map.Entry<String, Object> map : POJOfields.entrySet()) { if (map.getKey().equals(array[i])) { arrayList.add(map.getValue()); } } } if (array.length != arrayList.size()) { return '標題列數和實體類標記數不相同'; } try { //數據從序號1開始 int index = 1; //利用迭代器,遍歷集合數據,產生數據行 Iterator<T> it = list.iterator(); while (it.hasNext()) { row = sheet.createRow(index);// 默認的行數從0開始,為了統一格式設置從1開始,就是從excel的第二行開始 index++; T t = (T) it.next(); //System.out.println('t:' + t); for (int i = 0; i < arrayList.size(); i++) { String fieldName = (String) arrayList.get(i); //System.out.println(fieldName); String getMethodName = 'get' + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); //System.out.println(getMethodName); Class<? extends Object> tCls = t.getClass();// 泛型為Object以及所有Object的子類 //System.out.println(tCls); Method method = tCls.getMethod(getMethodName, new Class[]{});// 通過方法名得到對應的方法 //PropertyDescriptor pd = new PropertyDescriptor((String) arrayList.get(i), it.getClass()); //獲取成員變量的get方法 //Method method = pd.getWriteMethod(); Object value = method.invoke(t, new Object[]{});// 動態調用方,得到屬性值 //System.out.println(value.toString()); Cell cell = row.createCell(i); if (value != null) { if (value instanceof Date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat('yyyy-MM-dd'); value = simpleDateFormat.format(value); } cell.setCellValue(value.toString());// 為當前列賦值 cell.setCellStyle(dataStyle);//設置數據的樣式 } } } FileOutputStream fileOut = new FileOutputStream(path); wb.write(fileOut); fileOut.flush(); wb.close(); fileOut.close(); return 'success'; } catch (Exception e) { e.printStackTrace(); } return 'faile'; } /** * 獲取對應的實體類成員 */ private static LinkedHashMap<String, Object> getPOJOFieldAndValue(Object T) { //聲明返回結果集 LinkedHashMap<String, Object> result = new LinkedHashMap<>(); Field[] fields = T.getClass().getDeclaredFields();//獲取屬性名 if (fields != null) { for (Field field : fields) { excelRescoure Rescoure = field.getAnnotation(excelRescoure.class); if (Rescoure.value() != null && !''.equals(Rescoure.value())) { result.put(Rescoure.value(), field.getName()); } } } else { logger.warn('實體類:' + T + '不存在成員變量'); return null; } return result; } /**---------------------===================================================---------------------------**/ /** * 方法2: * HashMap數據寫入新建的excel * @path:excel文件路徑 * @array[]:文件首行數據列名,可為空,為空時不存在首行列名 * @List<Map<?,?>>:HashMap數據數列 * @key:hashmap里面的key值,需要一一對應列名的順序 * */ public static String writeToExcelByHashMap (String path, String[] array, List<HashMap> list,String[] key){ //創建工作薄 Workbook wb = new XSSFWorkbook(); /**標題和頁碼*/ CellStyle titleStyle = wb.createCellStyle(); // 設置單元格對齊方式 titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 //titleStyle.setVerticalAlignment(); // 默認垂直居中 // 設置字體樣式 Font titleFont = wb.createFont(); titleFont.setFontHeightInPoints((short) 12); // 字體高度 titleFont.setFontName('黑體'); // 字體樣式 titleStyle.setFont(titleFont); //創建sheet Sheet sheet = wb.createSheet('第一頁'); sheet.autoSizeColumn(0);// 自動設置寬度 // 在sheet中添加標題行 Row row = sheet.createRow((int) 0);// 行數從0開始 for (int i = 0; i < array.length; i++) { Cell cell = row.createCell(i); cell.setCellValue(array[i]); cell.setCellStyle(titleStyle); } /**數據樣式*/ // 數據樣式 因為標題和數據樣式不同 需要分開設置 不然會覆蓋 CellStyle dataStyle = wb.createCellStyle(); // 設置居中樣式 dataStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 /**數據寫入*/ //數據從序號1開始 try { int index = 1; for (int i = 0; i < list.size(); i++) { row = sheet.createRow(index);// 默認的行數從0開始,為了統一格式設置從1開始,就是從excel的第二行開始 index++; HashMap hashMap= list.get(i); for (int j = 0; j < key.length; j++) { Cell cell = row.createCell(j); cell.setCellValue(hashMap.get(key[j]).toString());// 為當前列賦值 cell.setCellStyle(dataStyle);//設置數據的樣式 } } FileOutputStream fileOut = new FileOutputStream(path); wb.write(fileOut); fileOut.flush(); wb.close(); fileOut.close(); return 'success'; }catch (Exception e){ e.printStackTrace(); } return 'faile'; } /**------------------===========================================================------------------------------------------------------*/ /** * 方法3: * HashMap數據寫入新建的excel * @path:excel文件路徑 * @array[]:文件首行數據列名,可為空,為空時不存在首行列名,列名需要和數列的數據順序一一對應 * @List<List>:數列數據數列 * * */ public static String writeToExcelByList(String path, String[] array, List<List> list){ //創建工作薄 Workbook wb = new XSSFWorkbook(); /**標題和頁碼*/ CellStyle titleStyle = wb.createCellStyle(); // 設置單元格對齊方式 titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 //titleStyle.setVerticalAlignment(); // 默認垂直居中 // 設置字體樣式 Font titleFont = wb.createFont(); titleFont.setFontHeightInPoints((short) 12); // 字體高度 titleFont.setFontName('黑體'); // 字體樣式 titleStyle.setFont(titleFont); //創建sheet Sheet sheet = wb.createSheet('第一頁'); sheet.autoSizeColumn(0);// 自動設置寬度 // 在sheet中添加標題行 Row row = sheet.createRow((int) 0);// 行數從0開始 for (int i = 0; i < array.length; i++) { Cell cell = row.createCell(i); cell.setCellValue(array[i]); cell.setCellStyle(titleStyle); } /**數據樣式*/ // 數據樣式 因為標題和數據樣式不同 需要分開設置 不然會覆蓋 CellStyle dataStyle = wb.createCellStyle(); // 設置居中樣式 dataStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 /**數據寫入*/ //數據從序號1開始 try { int index = 1; for (int i = 0; i < list.size(); i++) { row = sheet.createRow(index);// 默認的行數從0開始,為了統一格式設置從1開始,就是從excel的第二行開始 index++; List data= list.get(i); for (int j = 0; j < data.size(); j++) { Cell cell = row.createCell(j); cell.setCellValue(data.get(j).toString());// 為當前列賦值 cell.setCellStyle(dataStyle);//設置數據的樣式 } } FileOutputStream fileOut = new FileOutputStream(path); wb.write(fileOut); fileOut.flush(); wb.close(); fileOut.close(); return 'success'; }catch (Exception e){ e.printStackTrace(); } return 'faile'; }}5.測試類,同名的Excel會被覆蓋

package com.cly.utils.Excel;import java.util.*;/** * @author : CLy * @ClassName : WriteTest * @date : 2020/7/31 15:26 **/public class WriteTest { public static void main(String[] args) throws Exception { /**實體類測試 * writeToExcelByPOJO(String path, String[] array, List<T> list) * @path:excel文件路徑 * @array[]:文件首行數據列名,可為空,為空時不存在首行列名 * @list<T>:實體類數據數列 * 注意同名的Excel會被覆蓋,請寫好文件名字和對應的后綴 */ ExcelPOJO excelPOJO = new ExcelPOJO(); excelPOJO.setName('name'); excelPOJO.setPasswork('pass'); excelPOJO.setLook('look'); ExcelPOJO POJO2 = new ExcelPOJO(); POJO2.setName('name2'); POJO2.setPasswork('pass2'); POJO2.setLook('look2'); ExcelPOJO POJO3 = new ExcelPOJO(); POJO3.setName('name3'); POJO3.setPasswork('pass3'); POJO3.setLook('look3'); List<ExcelPOJO> list = new ArrayList<>(); list.add(excelPOJO); list.add(POJO2); list.add(POJO3); /**列名對應實體類中成員變量@excelRescoure的值,只需要寫入要的列明,不必全部成員變量都寫上*/ String[] arr = {'姓名', '密碼'}; String s = excelWrite.writeToExcelByPOJO('D:123.xls', arr, list); System.out.println(s); /**HashMap測試 * writeToExcelByHashMap (String path, String[] array, List<HashMap> list,String[] key) * @path:excel文件路徑 * @array[]:文件首行數據列名,可為空,為空時不存在首行列名 * @List<Map<?,?>>:HashMap數據數列 * @key:hashmap里面的key值,需要一一對應列名的順序 * 注意同名的Excel會被覆蓋,請寫好文件名字和對應的后綴 */ HashMap hashMap= new HashMap<>(); hashMap.put('1','q'); hashMap.put('0','w'); hashMap.put('5','e'); hashMap.put('2','r'); HashMap hashMap2= new HashMap<>(); hashMap2.put('1','q2'); hashMap2.put('0','w2'); hashMap2.put('5','e2'); hashMap2.put('2','r2'); /**列名順序*/ String[] arr2 = {'第一列','第二列','第三列','第四列'}; /**HashMap中的數據KEY對應列名順序,不存在列名或順序要求可隨意,但該數組數據必須要*/ String[] key = {'0','1','2','5'}; List list = new ArrayList(); list.add(hashMap); list.add(hashMap2); String s = excelWrite.writeToExcelByHashMap('D:123.xls', arr2, list,key); System.out.println(s); /**List測試 * writeToExcelByList(String path, String[] array, List<List> list) * @path:excel文件路徑 * @array[]:文件首行數據列名,可為空,為空時不存在首行列名,列名需要和數列的數據順序一一對應 * @List<List>:數列數據數列 * 注意同名的Excel會被覆蓋,請寫好文件名字和對應的后綴 */ String[] arr3 = {'第一列','第二列','第三列','第四列'}; List data = new ArrayList(); data.add('1'); data.add('2'); data.add('3'); data.add('4'); List data2 = new ArrayList(); data2.add('5'); data2.add('6'); data2.add('7'); data2.add('8'); List<List> list1 = new ArrayList(); list1.add(data); list1.add(data2); String s = excelWrite.writeToExcelByList('D:123.xls', arr3, list1); System.out.println(s); }}6.運行結果和說明

1.實體類測試結果

SpringBoot內存數據導出成Excel的實現方法SpringBoot內存數據導出成Excel的實現方法

2.HashMap測試

SpringBoot內存數據導出成Excel的實現方法

3.List測試

SpringBoot內存數據導出成Excel的實現方法

還有很多不足的地方,請多多指點,希望能給你帶來幫助。

SpringBoot實現Excel讀取在另一篇文章 文章地址:https://www.jb51.net/article/202762.htm

總結

到此這篇關于SpringBoot內存數據導出成Excel的文章就介紹到這了,更多相關SpringBoot內存數據導出成Excel內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: excel
相關文章:
主站蜘蛛池模板: 螺旋压榨机-刮泥机-潜水搅拌机-电动泥斗-潜水推流器-南京格林兰环保设备有限公司 | 深圳品牌设计公司-LOGO设计公司-VI设计公司-未壳创意 | 阻燃剂-氢氧化镁-氢氧化铝-沥青阻燃剂-合肥皖燃新材料 | 深圳律师咨询_深圳律师事务所_华荣【免费在线法律咨询】网 | 软启动器-上海能曼电气有限公司 真空搅拌机-行星搅拌机-双行星动力混合机-广州市番禺区源创化工设备厂 | 酒精检测棒,数显温湿度计,酒安酒精测试仪,酒精检测仪,呼气式酒精检测仪-郑州欧诺仪器有限公司 | 杭州实验室尾气处理_实验台_实验室家具_杭州秋叶实验设备有限公司 | 安全阀_弹簧式安全阀_美标安全阀_工业冷冻安全阀厂家-中国·阿司米阀门有限公司 | 精密光学实验平台-红外粉末压片机模具-天津博君 | 首页-瓜尔胶系列-化工单体系列-油田压裂助剂-瓜尔胶厂家-山东广浦生物科技有限公司 | 远程会诊系统-手术示教系统【林之硕】医院远程医疗平台 | MES系统工业智能终端_生产管理看板/安灯/ESOP/静电监控_讯鹏科技 | 吉林污水处理公司,长春工业污水处理设备,净水设备-长春易洁环保科技有限公司 | 不锈钢拉手厂家|浴室门拉手厂家|江门市蓬江区金志翔五金制品有限公司 | 外观设计_设备外观设计_外观设计公司_产品外观设计_机械设备外观设计_东莞工业设计公司-意品深蓝 | 实验室pH计|电导率仪|溶解氧测定仪|离子浓度计|多参数水质分析仪|pH电极-上海般特仪器有限公司 | 电子万能试验机_液压拉力试验机_冲击疲劳试验机_材料试验机厂家-济南众标仪器设备有限公司 | 拉力测试机|材料拉伸试验机|电子拉力机价格|万能试验机厂家|苏州皖仪实验仪器有限公司 | 电动高尔夫球车|电动观光车|电动巡逻车|电动越野车厂家-绿友机械集团股份有限公司 | 北京西风东韵品牌与包装设计公司,创造视觉销售力! | 阿里巴巴诚信通温州、台州、宁波、嘉兴授权渠道商-浙江联欣科技提供阿里会员办理 | 周易算网-八字测算网 - 周易算网-宝宝起名取名测名字周易八字测算网 | 国产频谱分析仪-国产网络分析仪-上海坚融实业有限公司 | 中央空调温控器_风机盘管温控器_智能_液晶_三速开关面板-中央空调温控器厂家 | 质检报告_CE认证_FCC认证_SRRC认证_PSE认证_第三方检测机构-深圳市环测威检测技术有限公司 | 北京浩云律师事务所-企业法律顾问_破产清算等公司法律服务 | 魔方网-培训咨询服务平台| 山东锐智科电检测仪器有限公司_超声波测厚仪,涂层测厚仪,里氏硬度计,电火花检漏仪,地下管线探测仪 | 铣床|万能铣床|立式铣床|数控铣床|山东滕州万友机床有限公司 | 全自动翻转振荡器-浸出式水平振荡器厂家-土壤干燥箱价格-常州普天仪器 | 袋式过滤器,自清洗过滤器,保安过滤器,篮式过滤器,气体过滤器,全自动过滤器,反冲洗过滤器,管道过滤器,无锡驰业环保科技有限公司 | 睿婕轻钢别墅_钢结构别墅_厂家设计施工报价 | 济南保安公司加盟挂靠-亮剑国际安保服务集团总部-山东保安公司|济南保安培训学校 | PCB设计,PCB抄板,电路板打样,PCBA加工-深圳市宏力捷电子有限公司 | 锂电混合机-新能源混合机-正极材料混料机-高镍,三元材料混料机-负极,包覆混合机-贝尔专业混合混料搅拌机械系统设备厂家 | 彩信群发_群发彩信软件_视频短信营销平台-达信通 | 压力喷雾干燥机,喷雾干燥设备,柱塞隔膜泵-无锡市闻华干燥设备有限公司 | 恒温水槽与水浴锅-上海熙浩实业有限公司 | 宜兴紫砂壶知识分享 - 宜兴壶人| 飞扬动力官网-广告公司管理软件,广告公司管理系统,喷绘写真条幅制作管理软件,广告公司ERP系统 | 手机存放柜,超市储物柜,电子储物柜,自动寄存柜,行李寄存柜,自动存包柜,条码存包柜-上海天琪实业有限公司 |