当前位置: 首页 > news >正文

easyexcel使用教程--导入导出简单案例

java中操作excel的库是poi,但是poi有很多问题,使用复杂,内存占用大等,阿里开源了一个操作excel的库叫easyexcel,它基于poi做了很多优化,平时读写excel建议使用这个库

文档地址: 关于Easyexcel | Easy Excel 官网

写入excel 

在实体类上写excel字段注解,ExcelProperty注解就是导出的列名,ExcelIgnoreUnannotated表示没加ExcelProperty注解的字段不会写入

@ExcelIgnoreUnannotated
@Getter
@Setter
@Schema(name = "User", description = "用户")
public class User implements Serializable {private static final long serialVersionUID = 1L;@TableId(value = "id", type = IdType.AUTO)private Integer id;@ExcelProperty("姓名")@Schema(description = "姓名")private String name;@ExcelProperty("金币数量")@Schema(description = "金币数量")private Integer coinNum;
}
    public void testWriteExcel() {String fileName = "d:/aaa.xlsx";List<User> users = new ArrayList<>();User user = new User();user.setName("张三");user.setCoinNum(100);users.add(user);user = new User();user.setName("李四");user.setCoinNum(200);users.add(user);// 写入本地excel文件EasyExcel.write(fileName, User.class).sheet("模板").doWrite(() -> {// 返回写入的数据return users;});}

可以看到,excel数据成功写入了,但是标题换行了,如果想标题不换行可以指定列宽,使用ColumnWidth注解,加在类上面表示所有列宽度都是这个数值,也可以加到指定字段上

 导出excel

写法跟写入excel差不多,这里加了个出错返回json,这样出错了前端可以给出提示

@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("download")public void download(HttpServletResponse response) throws IOException {// 导出excel如果失败会返回jsontry {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");// 这里需要设置不关闭流,这样失败了可以返回jsonEasyExcel.write(response.getOutputStream(), User.class).autoCloseStream(Boolean.FALSE).sheet("模板").doWrite(userService.list());} catch (Exception e) {// 重置responseresponse.reset();response.setContentType("application/json");response.setCharacterEncoding("utf-8");Map<String, String> map = MapUtils.newHashMap();map.put("status", "failure");map.put("message", "下载文件失败" + e.getMessage());response.getWriter().println(JSON.toJSONString(map));}}
}

读取excel

这里推荐使用PageRead,默认一次读取100条

    @Testpublic void testPageRead() {String fileName = "d:/aaa.xlsx";// 这里默认每次会读取100条数据// 具体需要返回多少行可以在`PageReadListener`的构造函数设置EasyExcel.read(fileName, User.class, new PageReadListener<User>(dataList -> {for (User demoData : dataList) {log.info("读取到一条数据{}", JSON.toJSONString(demoData));}})).sheet().doRead();}

导入excel

导入也跟读取excel类似,使用MultipartFile接收excel文件,使用PageReadListener读取数据

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {@Autowiredprivate UserService userService;@PostMapping("upload")public Result upload(@RequestPart MultipartFile file) throws IOException {EasyExcel.read(file.getInputStream(), User.class, new PageReadListener<User>(users -> {userService.saveBatch(users);})).sheet().doRead();return resultOk();}
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 第十二章:设置pod和容器权限-保障集群内节点和⽹络安全
  • “微软蓝屏”事件敲响网络安全的警钟
  • C++(2)(数据的共享与保护)
  • Go语言入门
  • Linux安全与高级应用(四)深入探索MySQL数据库:安装、管理与安全实践
  • Journyx项目管理软件 soap_cgi.pyc XXE漏洞复现
  • 【限流与Sentinel超详细分析】
  • 4.8.双向循环神经网络
  • 【C++综合项目】——基于Boost库的搜索引擎(手把手讲解,小白一看就会!!)
  • 前端web开发HTML+CSS3+移动web(0基础,超详细)——第4天
  • priority_queue模拟实现【C++】
  • FFmpeg源码:av_realloc、av_reallocp、size_mult、av_realloc_f函数分析
  • Springboot 开发之 Quartz 任务调度框架简介
  • 自定义View-- wifi强度
  • 从0开始搭建vue + flask 旅游景点数据分析系统( 六):搭建后端flask框架
  • 【162天】黑马程序员27天视频学习笔记【Day02-上】
  • AWS实战 - 利用IAM对S3做访问控制
  • CSS中外联样式表代表的含义
  • HTML中设置input等文本框为不可操作
  • HTTP中GET与POST的区别 99%的错误认识
  • IOS评论框不贴底(ios12新bug)
  • Mysql数据库的条件查询语句
  • Python中eval与exec的使用及区别
  • react 代码优化(一) ——事件处理
  • 给第三方使用接口的 URL 签名实现
  • 关于Java中分层中遇到的一些问题
  • 简单基于spring的redis配置(单机和集群模式)
  • 如何正确配置 Ubuntu 14.04 服务器?
  • AI又要和人类“对打”,Deepmind宣布《星战Ⅱ》即将开始 ...
  • 京东物流联手山西图灵打造智能供应链,让阅读更有趣 ...
  • ​Base64转换成图片,android studio build乱码,找不到okio.ByteString接腾讯人脸识别
  • ​用户画像从0到100的构建思路
  • # Apache SeaTunnel 究竟是什么?
  • #define、const、typedef的差别
  • #include
  • (C++20) consteval立即函数
  • (pojstep1.1.1)poj 1298(直叙式模拟)
  • (办公)springboot配置aop处理请求.
  • (计算机网络)物理层
  • (每日持续更新)jdk api之StringBufferInputStream基础、应用、实战
  • (一)、软硬件全开源智能手表,与手机互联,标配多表盘,功能丰富(ZSWatch-Zephyr)
  • (一)Java算法:二分查找
  • *1 计算机基础和操作系统基础及几大协议
  • .bat批处理出现中文乱码的情况
  • .NET 8 跨平台高性能边缘采集网关
  • .NET 8 中引入新的 IHostedLifecycleService 接口 实现定时任务
  • .NET CLR Hosting 简介
  • .Net Core与存储过程(一)
  • .net web项目 调用webService
  • .NET 的静态构造函数是否线程安全?答案是肯定的!
  • .Net 基于MiniExcel的导入功能接口示例
  • .NET/C#⾯试题汇总系列:⾯向对象
  • .net6解除文件上传限制。Multipart body length limit 16384 exceeded
  • .NET关于 跳过SSL中遇到的问题
  • .vimrc 配置项