从excel导入到excel(史上最全的Excel导入导出)
从excel导入到excel(史上最全的Excel导入导出)
2024-06-26 05:47:30  作者:寂寞式想念  网址:https://m.xinb2b.cn/sport/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的数据

从excel导入到excel(史上最全的Excel导入导出)(1)

从excel导入到excel(史上最全的Excel导入导出)(2)

获取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);

结果

从excel导入到excel(史上最全的Excel导入导出)(3)

模型映射导出

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-06-26最新转正工作总结最新转正工作总结(集锦5篇)【篇一】  在促销过程中,促销技巧非常重要,是能决定你的销量和产品推广的基石试用期工作总结范文我们在促销过程中要充分运用各种各样的促销技巧以实现我们的促销目的  1.主动热。
  • 拾起一片片春意作文(春意盎然几篇作文有用拿去用)
  • 2024-06-26春意盎然几篇作文有用拿去用#春日生活打卡季#无论是在学校还是在社会中,许多人都写过作文吧,作文可分为小学作文、中学作文、大学作文(论文)相信写作文是一个让许多人都头痛的问题,以下是小编收集整理的春意盎然作文,欢迎大家借鉴与参考。
  • 国外教授等级(轻松阅读各国晋升教授)
  • 2024-06-26轻松阅读各国晋升教授各国晋升教授,要花多少年?来源:本文转载自青塔人才,已获得授权微信平台编辑:周悦这几年,“90后”教授、博导越来越多了,多到让人产生自我怀疑但能一路直升的毕竟是少数,且不说曾有六旬副教授数次晋升失败的。
  • 亲情的句子说说心情(珍惜亲情的句子说说心情)
  • 2024-06-26珍惜亲情的句子说说心情亲情,在你还没有来到这个世界前就先期而至,并时刻伴随你渡过慢慢人生征程,等到你无疾而终悄然离开这个世界后,可他依然默默流趟,所以请珍惜亲情从婴儿呱呱坠地,父母含辛茹苦,捧在手上怕冻着,含在嘴里怕化了营。
  • 为什么说养鹅以后有前景(养鹅利润非常高)
  • 2024-06-26养鹅利润非常高正文:大鹅,对于我们农村人来说是再熟悉不过的一种“凶兽”,为什么这么说呢?因为在农村小孩眼里,大鹅、大公鸡、土狗在农村都属于“村霸级别的凶兽”,很多农村小孩都被这些动物给欺负过,甚至还留下了阴影但是对。
  • 怎样去除铜锅上的黑渍
  • 2024-06-26怎样去除铜锅上的黑渍人靠打扮,家靠收拾长期深耕家居领域的我,今天推荐的都是家居清洁中你那个常用的清洁神器1.洗涤剂主要处理食物粘底造成的烧焦渍就是这款洗涤剂啦~解决方法:1.可以先把锅长时间浸泡在热水中,至烧焦物软化后再。
  • 大明王朝1566的历史背景(架构历史探讨复杂人性)
  • 2024-06-26架构历史探讨复杂人性《大明王朝1566》是一部十几年前播出的电视剧当时,收视率并不好随着时间的推移,这部电视剧重新走入观众视线,口碑爆棚,完成了逆袭这其中的因素很多不可否认的一点是:观众对历史感兴趣,对明朝的历史感兴趣这。
  • 盛唐幻夜结局播出时间(新剧盛唐幻夜开播几天播放破亿)
  • 2024-06-26新剧盛唐幻夜开播几天播放破亿最近大家都在追新剧《盛唐幻夜》,据悉《盛唐幻夜》开播才几天点击过亿播放了!想想当下没有流量明星的剧能有这个成绩确实令人有点意外!反观一些盛行的网剧要么剧本不行,要么就是演员的演技都尬的一批而小编对这部。
  • 涝灾对植物的影响(洪涝对林木的影响)
  • 2024-06-26洪涝对林木的影响【六月以来,江淮流域遭受严重洪涝灾害,给林业生产造成严重伤害,目前正是灾后恢复最佳时期,拜读安徽省林科院胡一民教授《洪涝对林木的影响、急救措施及诱发病虫害的防治技术》一文,内容丰富,操作性强,非常实用。
  • 回到经典桌面(回到经典Windows95)
  • 2024-06-26回到经典Windows95RetroBar是一款Windows怀旧软件,它能够让现代Windows任务栏变成Windows95、98、Me、2000或XP风格的Windows任务栏,即开即用,但并没有开始菜单,一下就露馅Ret。