从excel导入到excel(史上最全的Excel导入导出)
从excel导入到excel(史上最全的Excel导入导出)
2024-11-05 03:19:17  作者:寂寞式想念  网址:https://m.xinb2b.cn/know/idp425234.html

喝水不忘挖井人,感谢阿里巴巴项目组提供了easyexcel工具类,github地址:

http://github.com/alibaba/easyexcel

文章目录环境搭建读取excel文件默认读取指定读取默认读取指定读取小于1000行数据大于1000行数据导出excle无模型映射导出模型映射导出单个Sheet导出多个Sheet导出工具类测试类环境搭建easyexcel 依赖(必须)springboot (不是必须)lombok (不是必须)

<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.2-beat1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.2</version> </dependency>

读取excel文件小于1000行数据默认读取

读取Sheet1的全部数据

String filePath = "/home/chenmingjian/Downloads/学生表.xlsx"; List<Object> objects = excelUtil.readLessThan1000Row(FilePath);

指定读取

如果您正在学习Spring Boot,推荐一个连载多年还在继续更新的免费教程:http://blog.didispace.com/spring-boot-learning-2x/

下面是学生表.xlsx中Sheet1,Sheet2的数据



获取Sheet1表头以下的信息

String filePath = "/home/chenmingjian/Downloads/学生表.xlsx";//第一个1代表sheet1, 第二个1代表从第几行开始读取数据,行号最小值为0Sheet sheet = new Sheet(1, 1);List<Object> objects = ExcelUtil.readLessThan1000Row(filePath,sheet);

获取Sheet2的所有信息

String filePath = "/home/chenmingjian/Downloads/学生表.xlsx"; Sheet sheet = new Sheet(2, 0); List<Object> objects = ExcelUtil.readLessThan1000Row(filePath,sheet);

大于1000行数据默认读取

String filePath = "/home/chenmingjian/Downloads/学生表.xlsx";List<Object> objects = ExcelUtil.readMoreThan1000Row(filePath);

指定读取

String filePath = "/home/chenmingjian/Downloads/学生表.xlsx";Sheet sheet = new Sheet(1, 2);List<Object> objects = ExcelUtil.readMoreThan1000Row(filePath,sheet);

导出excle单个Sheet导出无模型映射导出

String filePath = "/home/chenmingjian/Downloads/测试.xlsx";List<List<Object>> data = new ArrayList<>();data.add(Arrays.asList("111","222","333"));data.add(Arrays.asList("111","222","333"));data.add(Arrays.asList("111","222","333"));List<String> head = Arrays.asList("表头1", "表头2", "表头3");ExcelUtil.writeBySimple(filePath,data,head);

结果


模型映射导出

1、定义好模型对象

package com.springboot.utils.excel.test;import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.metadata.BaseRowModel;import lombok.Data;import lombok.EqualsAndHashCode;@EqualsAndHashCode(callSuper = true)@Datapublic class TableHeaderExcelProperty extends BaseRowModel { @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄",index = 1) private int age; @ExcelProperty(value = "学校",index = 2) private String school;}

2、调用方法

String filePath = "/home/chenmingjian/Downloads/测试.xlsx";ArrayList<TableHeaderExcelProperty> data = new ArrayList<>(); for(int i = 0; i < 4; i ){ TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty(); tableHeaderExcelProperty.setName("cmj" i); tableHeaderExcelProperty.setAge(22 i); tableHeaderExcelProperty.setSchool("清华大学" i); data.add(tableHeaderExcelProperty); } ExcelUtil.writeWithTemplate(filePath,data);

多个Sheet导出

1、定义好模型对象

package com.springboot.utils.excel.test;import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.metadata.BaseRowModel;import lombok.Data;import lombok.EqualsAndHashCode;@EqualsAndHashCode(callSuper = true)@Datapublic class TableHeaderExcelProperty extends BaseRowModel { @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄",index = 1) private int age; @ExcelProperty(value = "学校",index = 2) private String school;}

2、调用方法

ArrayList<ExcelUtil.MultipleSheelPropety> list1 = new ArrayList<>(); for(int j = 1; j < 4; j ){ ArrayList<TableHeaderExcelProperty> list = new ArrayList<>(); for(int i = 0; i < 4; i ){ TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty(); tableHeaderExcelProperty.setName("cmj" i); tableHeaderExcelProperty.setAge(22 i); tableHeaderExcelProperty.setSchool("清华大学" i); list.add(tableHeaderExcelProperty); } Sheet sheet = new Sheet(j, 0); sheet.setSheetName("sheet" j); ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety(); multipleSheelPropety.setData(list); multipleSheelPropety.setSheet(sheet); list1.add(multipleSheelPropety); } ExcelUtil.writeWithMultipleSheel("/home/chenmingjian/Downloads/aaa.xlsx",list1);

工具类

另外,如果您正在学习Spring Cloud,推荐一个连载多年还在继续更新的免费教程:http://blog.didispace.com/spring-cloud-learning/

package com.springboot.utils.excel;import com.alibaba.excel.EasyExcelFactory;import com.alibaba.excel.ExcelWriter;import com.alibaba.excel.context.AnalysisContext;import com.alibaba.excel.event.AnalysisEventListener;import com.alibaba.excel.metadata.BaseRowModel;import com.alibaba.excel.metadata.Sheet;import lombok.Data;import lombok.Getter;import lombok.Setter;import lombok.extern.slf4j.Slf4j;import org.springframework.util.CollectionUtils;import org.springframework.util.StringUtils;import java.io.*;import java.util.ArrayList;import java.util.Collections;import java.util.List;@Slf4jpublic class ExcelUtil { private static Sheet initSheet; static { initSheet = new Sheet(1, 0); initSheet.setSheetName("sheet"); //设置自适应宽度 initSheet.setAutoWidth(Boolean.TRUE); } public static List<Object> readLessThan1000Row(String filePath){ return readLessThan1000RowBySheet(filePath,null); } public static List<Object> readLessThan1000RowBySheet(String filePath, Sheet sheet){ if(!StringUtils.hasText(filePath)){ return null; } sheet = sheet != null ? sheet : initSheet; InputStream fileStream = null; try { fileStream = new FileInputStream(filePath); return EasyExcelFactory.read(fileStream, sheet); } catch (FileNotFoundException e) { log.info("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(fileStream != null){ fileStream.close(); } } catch (IOException e) { log.info("excel文件读取失败, 失败原因:{}", e); } } return null; } public static List<Object> readMoreThan1000Row(String filePath){ return readMoreThan1000RowBySheet(filePath,null); } public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet){ if(!StringUtils.hasText(filePath)){ return null; } sheet = sheet != null ? sheet : initSheet; InputStream fileStream = null; try { fileStream = new FileInputStream(filePath); ExcelListener excelListener = new ExcelListener(); EasyExcelFactory.readBySax(fileStream, sheet, excelListener); return excelListener.getDatas(); } catch (FileNotFoundException e) { log.error("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(fileStream != null){ fileStream.close(); } } catch (IOException e) { log.error("excel文件读取失败, 失败原因:{}", e); } } return null; } public static void writeBySimple(String filePath, List<List<Object>> data, List<String> head){ writeSimpleBySheet(filePath,data,head,null); } public static void writeSimpleBySheet(String filePath, List<List<Object>> data, List<String> head, Sheet sheet){ sheet = (sheet != null) ? sheet : initSheet; if(head != null){ List<List<String>> list = new ArrayList<>(); head.forEach(h -> list.add(Collections.singletonList(h))); sheet.setHead(list); } OutputStream outputStream = null; ExcelWriter writer = null; try { outputStream = new FileOutputStream(filePath); writer = EasyExcelFactory.getWriter(outputStream); writer.write1(data,sheet); } catch (FileNotFoundException e) { log.error("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(writer != null){ writer.finish(); } if(outputStream != null){ outputStream.close(); } } catch (IOException e) { log.error("excel文件导出失败, 失败原因:{}", e); } } } public static void writeWithTemplate(String filePath, List<? extends BaseRowModel> data){ writeWithTemplateAndSheet(filePath,data,null); } public static void writeWithTemplateAndSheet(String filePath, List<? extends BaseRowModel> data, Sheet sheet){ if(CollectionUtils.isEmpty(data)){ return; } sheet = (sheet != null) ? sheet : initSheet; sheet.setClazz(data.get(0).getClass()); OutputStream outputStream = null; ExcelWriter writer = null; try { outputStream = new FileOutputStream(filePath); writer = EasyExcelFactory.getWriter(outputStream); writer.write(data,sheet); } catch (FileNotFoundException e) { log.error("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(writer != null){ writer.finish(); } if(outputStream != null){ outputStream.close(); } } catch (IOException e) { log.error("excel文件导出失败, 失败原因:{}", e); } } } public static void writeWithMultipleSheel(String filePath,List<MultipleSheelPropety> multipleSheelPropetys){ if(CollectionUtils.isEmpty(multipleSheelPropetys)){ return; } OutputStream outputStream = null; ExcelWriter writer = null; try { outputStream = new FileOutputStream(filePath); writer = EasyExcelFactory.getWriter(outputStream); for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) { Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet; if(!CollectionUtils.isEmpty(multipleSheelPropety.getData())){ sheet.setClazz(multipleSheelPropety.getData().get(0).getClass()); } writer.write(multipleSheelPropety.getData(), sheet); } } catch (FileNotFoundException e) { log.error("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(writer != null){ writer.finish(); } if(outputStream != null){ outputStream.close(); } } catch (IOException e) { log.error("excel文件导出失败, 失败原因:{}", e); } } } @Data public static class MultipleSheelPropety{ private List<? extends BaseRowModel> data; private Sheet sheet; } @Getter @Setter public static class ExcelListener extends AnalysisEventListener { private List<Object> datas = new ArrayList<>(); @Override public void invoke(Object object, AnalysisContext context) { //当前行 // context.getCurrentRowNum() if (object != null) { datas.add(object); } } @Override public void doAfterAllAnalysed(AnalysisContext context) { //解析结束销毁不用的资源 } } }

测试类

package com.springboot.utils.excel;import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.metadata.BaseRowModel;import com.alibaba.excel.metadata.Sheet;import lombok.Data;import lombok.EqualsAndHashCode;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.util.ArrayList;import java.util.Arrays;import java.util.List;@SpringBootTest@RunWith(SpringRunner.class)public class Test { @org.junit.Test public void readLessThan1000Row(){ String filePath = "/home/chenmingjian/Downloads/测试.xlsx"; List<Object> objects = ExcelUtil.readLessThan1000Row(filePath); objects.forEach(System.out::println); } @org.junit.Test public void readLessThan1000RowBySheet(){ String filePath = "/home/chenmingjian/Downloads/测试.xlsx"; Sheet sheet = new Sheet(1, 1); List<Object> objects = ExcelUtil.readLessThan1000RowBySheet(filePath,sheet); objects.forEach(System.out::println); } @org.junit.Test public void readMoreThan1000Row(){ String filePath = "/home/chenmingjian/Downloads/测试.xlsx"; List<Object> objects = ExcelUtil.readMoreThan1000Row(filePath); objects.forEach(System.out::println); } @org.junit.Test public void writeBySimple(){ String filePath = "/home/chenmingjian/Downloads/测试.xlsx"; List<List<Object>> data = new ArrayList<>(); data.add(Arrays.asList("111","222","333")); data.add(Arrays.asList("111","222","333")); data.add(Arrays.asList("111","222","333")); List<String> head = Arrays.asList("表头1", "表头2", "表头3"); ExcelUtil.writeBySimple(filePath,data,head); } @org.junit.Test public void writeWithTemplate(){ String filePath = "/home/chenmingjian/Downloads/测试.xlsx"; ArrayList<TableHeaderExcelProperty> data = new ArrayList<>(); for(int i = 0; i < 4; i ){ TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty(); tableHeaderExcelProperty.setName("cmj" i); tableHeaderExcelProperty.setAge(22 i); tableHeaderExcelProperty.setSchool("清华大学" i); data.add(tableHeaderExcelProperty); } ExcelUtil.writeWithTemplate(filePath,data); } @org.junit.Test public void writeWithMultipleSheel(){ ArrayList<ExcelUtil.MultipleSheelPropety> list1 = new ArrayList<>(); for(int j = 1; j < 4; j ){ ArrayList<TableHeaderExcelProperty> list = new ArrayList<>(); for(int i = 0; i < 4; i ){ TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty(); tableHeaderExcelProperty.setName("cmj" i); tableHeaderExcelProperty.setAge(22 i); tableHeaderExcelProperty.setSchool("清华大学" i); list.add(tableHeaderExcelProperty); } Sheet sheet = new Sheet(j, 0); sheet.setSheetName("sheet" j); ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety(); multipleSheelPropety.setData(list); multipleSheelPropety.setSheet(sheet); list1.add(multipleSheelPropety); } ExcelUtil.writeWithMultipleSheel("/home/chenmingjian/Downloads/aaa.xlsx",list1); } @EqualsAndHashCode(callSuper = true) @Data public static class TableHeaderExcelProperty extends BaseRowModel { @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄",index = 1) private int age; @ExcelProperty(value = "学校",index = 2) private String school; } }

作者 | 冲奶粉的奶爸

来源 | http://blog.csdn.net/qq_32258777/article/details/89031479

  • 上官婉儿在历史上算个好宰相吗(从婢女到女宰相)
  • 2024-11-05从婢女到女宰相1995年,古装剧《武则天》播出当时这部剧收视率很高该剧讲述的是武则天从一个宫女成为一代女皇的故事刘晓庆、陈宝国、茹萍主演对于武则天的故事,大多数人耳熟能详,但是关于武则天一手捧起来的上官婉儿,我想对。
  • 祛痘方法有哪些快速祛痘(怎么样科学祛痘)
  • 2024-11-05怎么样科学祛痘1:祛痘的基本原理祛痘的基本原理是什么?祛痘的基本原理是清除皮肤上的油脂和污垢,使皮肤毛孔通畅,同时杀死细菌这些都是导致粉刺、痘痘形成的主要原因那么如何有效祛痘呢?其实方法很多,但是最有效的方法还是常。
  • 万州烤鱼的七种口味(风靡全国的万州烤鱼)
  • 2024-11-05风靡全国的万州烤鱼万州烤鱼是重庆特色传统名菜制作万州烤鱼时把鱼清洗干净后先用木炭烧烤,然后再盛到铁盘中,浇上特制的底料,再放上西芹、豆芽等配菜最后撒上点香菜,那浓浓的香辣咸鲜味,总是让人一口一口吃得停不下来!万州烤鱼在。
  • 手斗和簸箕的说法顺口溜(十指簸萁没有斗)
  • 2024-11-05十指簸萁没有斗在农村,我们总是可以听到很多关于簸箕和斗是老俗话,这两个东西原本是我们农村日常生活中的工具,簸箕是用来簸东西中的杂物的,比如我们收获的黄豆、小麦等,在将他们收藏装袋的时候都需要簸出不干净的比较轻的杂质。
  • 尼尔机械纪元2b 手办现货(机械纪元2B造型手办公开)
  • 2024-11-05机械纪元2B造型手办公开最近,MOONLIGHTSTUDIO推出了《尼尔:机械纪元》中2B的手办,包含正常以及爆衣形态的两个版本,手办为1:4比例,全高51厘米,非常好看其中,手办面罩和左手可以拆卸,左手拥有压裙和支撑两种姿。
  • 马齿苋敷脸每天多长为最佳时间(马齿苋敷脸的正确方法)
  • 2024-11-05马齿苋敷脸的正确方法一般来说,马齿苋敷脸一周2-3次为宜,另外,敷脸的时间不宜过长,5-10分钟即可马齿苋敷脸的正确方法:⑴准备马齿苋适量,将表面泥沙清洗干净⑵在锅中放入适量的水,将马齿苋放入,小火煮5分钟后,捞出⑶将煮。
  • 刘利生最新篆刻作品(刘存发篆刻欣赏)
  • 2024-11-05刘存发篆刻欣赏每日新报数字报刊平台-新赏析作者简介刘存发,1963年2月生,天津华厦建筑设计有限公司董事长正高级工程师、注册城市规划师、全国一级注册建筑师,“全国勘察设计行业优秀企业家”、“中国好人”荣誉获得者,。
  • 30多岁适合用什么牌子眼霜(30岁哪个牌子眼霜好用)
  • 2024-11-0530岁哪个牌子眼霜好用眼霜能够延缓眼部皮肤的衰老,不同年纪适合的眼霜也不一样,那么30岁适合什么眼霜呢?下面一起来看看好用的30岁眼霜推荐吧!Fancl活肤紧致凝亮眼霜白色乳霜质地,没有流动性但涂抹的时候就发现质地其实很柔。
  • 玉帝传承什么思想(玉帝究竟是何来历)
  • 2024-11-05玉帝究竟是何来历#国风大典#玉皇大帝又被民间百姓亲切地称为:老天爷、天公、玉皇上帝等,大家应该在生活中经常听到一句俗语:天公不作美,或者古装电视剧中的百姓为了庄稼祈雨,嘴里念叨着:求老天爷庇佑,这些话都是古代百姓说给。