一、将10万条数据从Excel读取出来

读取支持多标题,我们只需要指定最后一行的标题的行号即可,例如上述excel标题的行号为1,因此需要设置headRowNumber为1。

定义User 类,使用User类映射excel单条记录, 使用ExcelProperty注解标注excel里的字段名称。

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import lombok.ToString;@Data
@ToString
public class User {@ExcelProperty("id")private String id;@ExcelProperty("用户名")private String userName;@ExcelProperty("地址")private String address;}

FileUtil:

public class FileUtil {public static String getResourcePath() {return FileUtil.class.getResource("/").getPath();}}

执行读取,指定read方法的三个重要参数: file对象, 映射的pojo对象,读取监听器。

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.read.listener.PageReadListener;
import lombok.Data;
import lombok.ToString;
import org.junit.Test;import java.io.File;public class ExcelReadWriteTest{@Testpublic void readData() {File file = new File(FileUtil.getResourcePath() + "demo.xlsx");if (file.exists()) {long start = System.currentTimeMillis();EasyExcel.read(file, User.class, new PageReadListener<User>(dataList -> {for (User user : dataList) {System.out.println(user);}})).headRowNumber(1).sheet().doRead();System.out.println("总耗时:" + (System.currentTimeMillis() - start) / 1000 + " s");}}
}

检查第一条数据是否正确:

总耗时1S:

二、将10万条数据写入到Excel

先看下写入的效果,单标题和多标题的区别。

1. 单标题

2. 多标题

完整代码

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import org.junit.Test;import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;public class ExcelReadWriteTest {@Testpublic void readData() {File file = new File(FileUtil.getResourcePath() + "demo.xlsx");if (file.exists()) {long start = System.currentTimeMillis();EasyExcel.read(file, User.class, new PageReadListener<User>(dataList -> {for (User user : dataList) {System.out.println(user);}})).headRowNumber(1).sheet().doRead();System.out.println("总耗时:" + (System.currentTimeMillis() - start) / 1000 + " s");}}@Testpublic void WriteData() throws IOException {File file = new File(FileUtil.getResourcePath() + "test01.xlsx");if (!file.exists()) {file.createNewFile();}EasyExcel.write(file, User.class).head(head()).sheet("用户表").doWrite(() -> data());}@Testpublic void WriteData0() throws IOException {File file = new File(FileUtil.getResourcePath() + "test02.xlsx");if (!file.exists()) {file.createNewFile();}EasyExcel.write(file, User.class).head(manyHead()).sheet("用户表").doWrite(() -> data());}//单行标题private List<List<String>> head() {List<List<String>> head = new ArrayList<>();head.add(Arrays.asList("id"));head.add(Arrays.asList("用户名"));head.add(Arrays.asList("地址"));return head;}// 多行标题private List<List<String>> manyHead() {List<List<String>> head = new ArrayList<>();head.add(Arrays.asList("用户", "id"));head.add(Arrays.asList("用户", "用户名"));head.add(Arrays.asList("用户", "地址"));return head;}private List<User> data() {List<User> userList = new ArrayList<>();for (int i = 0; i < 100000; i++) {User user = new User();user.setId(i + "");user.setUserName("zhangsan" + i);user.setAddress("shanghai" + i);userList.add(user);}return userList;}}

三、上传和下载excel

可以新建一个SpringBoot工程,使用接口测试上传和下载功能。

1. 上传10万条数据

写要给upLoad接口,同时指定下excel里的标题所在行号。

   @PostMapping("/upLoad")public String uploadExcel(MultipartFile file, Integer headRowNumber) throws IOException {//指定headRowNumberEasyExcel.read(file.getInputStream(), User.class, new UploadListener(userService)).headRowNumber(headRowNumber).sheet().doRead();return "success";}

指定一个上传监听器,用于文件的回调处理。

package com.example;import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;public class UploadListener implements ReadListener<User> {private static Logger logger = LoggerFactory.getLogger(UploadListener.class);private UserService userService;private List<User> cacheLists = new ArrayList<>(100);public UploadListener(UserService userService) {this.userService = userService;}@Overridepublic void invoke(User data, AnalysisContext context) {logger.info("解析到一条数据: {}", JSON.toJSONString(data));cacheLists.add(data);if (cacheLists.size() > 100) {saveData();cacheLists = ListUtils.newArrayListWithExpectedSize(100);}}private void saveData() {logger.info("存储数据" + cacheLists.size() + "条!");}@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {if (CollectionUtils.isNotEmpty(cacheLists)) {saveData();logger.info("所有数据解析完成!");}}
}

用postman测试

查看第一条数据id为0, 说明上传正确。

2. 下载10万条数据

指定sheet名称,同时将URL用UTF-8编码,防止文件名导出出现乱码的情况。

    @PostMapping("/downLoad")public String downloadExcel(HttpServletResponse response) throws IOException {response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");// 如果指定了ExcelProperty,那么可以不用不用指定head,到处的excel仍然含有标题,如果想要多标题,那么就需要指定EasyExcel.write(response.getOutputStream(), User.class).sheet("用户表").doWrite(data());return "success";}

用postman测试

保存到本地,可以打开说明下载正确!

代码地址: https://gitee.com/bingbing-123456/easyexcel_practice

如果链接打不开,可私信找我。

EasyExcel专题(一) Excel 读取、写入、上传和下载相关推荐

  1. excel表格的上传和下载

    excel表格的上传和下载 excel的表格用到了xlsx插件, 下载npm install xlsx.js 引入 import xlsx from 'xlsx' Utils.js写的公共方法 //把 ...

  2. java 上传 excel_Java对Excel表格的上传和下载处理方法

    Excel表格文件的上传和下载,java中涉及到文件肯定会有io流的知识. 而excel文件就要涉及到poi技术,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为 ...

  3. java中excel上传_java对excel表格的上传和下载处理

    Excel表格文件的上传和下载,java中涉及到文件肯定会有io流的知识. 而excel文件就要涉及到poi技术,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为 ...

  4. HuTool工具包实现Excel文件的上传、下载以及修改文件名称

    加载依赖文件 <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</ar ...

  5. sap中Excel的模版上传和下载

    一:所用到的事物码: smw0 二:上传步骤 三:下载代码 TABLES:sscrfields. *定义OLE变量 DATA:g_excel TYPE ole2_object,      g_appl ...

  6. vue实现Excel文件的上传与下载

    参考:https://www.cnblogs.com/wnxyz8023/p/11101771.html 转载于:https://www.cnblogs.com/Samuel-Leung/p/1110 ...

  7. Excel 上传和下载

    前言 相信很多前端小伙伴在开发后台管理系统的时候都会遇到这样的需求,上传或者下载 excel 表格:为什么会出现这样的需求呀,因为我们知道后台管理系统中莫非功能就是查看,删除,修改,添加,但是所谓的添 ...

  8. Vue实现Excel模板文件的上传与下载

    Vue实现Excel模板文件的上传与下载 一.前言 越来越多的项目开始使用前后端分离的方式来进行开发了,前端使用的vue来进行页面处理的,所以正常的文件下载和上传肯定是少不了的,因为这也是自己第一次使 ...

  9. EasyExcel+elementUI+vue 上传、下载文件实例

    本文为 easyexcel使用具体实例,包含前后端代码,前端使用 vue + elementUI+axios,后端使用 spring boot. 1. 上传文件 1.1. 后端 1.1.1. 添加依赖 ...

最新文章

  1. 华为js面试题_四面腾讯与华为,大厂前端面试真BT!
  2. 十天学Linux内核之第二天---进程
  3. linux 文本搜索命令 grep egrep fgrep 区别
  4. 题目1204:农夫、羊、菜和狼的故事
  5. Caffe学习系列(4):激活层(Activiation Layers)及参数
  6. 计算机教育杂志社投稿送样刊,山东教育杂志社投稿期刊论文征稿发表-陶润杂志网...
  7. 异常解决(二)-- AttributeError: cannot assign module before Module.__init__() call
  8. Unity 新手入门 如何理解协程 IEnumerator yield
  9. 弹窗php整人_[整人小程序] 超级信息框(无限弹窗++)
  10. 解决:Please specify a different SDK name--PyCharm报错
  11. String str=“i“与 String str=new String(“i”)一样吗?
  12. GitHub 公开 B 站寄来的 DMCA 删除通知
  13. NGUI_2.6.3_系列教程三
  14. 1.java数组教程及示例知乎
  15. 苹果Mac如何使用Tuxera NTFS 格式化磁盘?
  16. ubuntu 在线安装最新交叉编译工具
  17. MySQL中删除表中并不存在的数据不报错
  18. ITK-SNAP自动分割应用示例:如何进行乳腺腺体脂肪体积测量
  19. u盘装服务器系统还原c盘失败,usb启动盘安装系统还原失败怎么办?
  20. 判断一个很大的数是否是11的倍数(2种做法)

热门文章

  1. 【yoyo】类,对象,方法,属性,事件的定义
  2. arm64 blr指令
  3. Discuz论坛搬家教程
  4. 关于C语言网络编程(Linux)的初学习。
  5. 用于光波导耦合的倾斜光栅分析
  6. 公众号群发消息 permission for this msgtype hint: [BdFhTa06992277]
  7. 微信小程序 - 小技巧
  8. **官网被黑、网站被黑后和网站被入侵更好的处理解决办法
  9. 服务器ftp日志文件在哪里,ftp服务器的日志在哪
  10. [附源码]java毕业设计在线视频网站