导出:

package com.example.demo.excel.demo0;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.NumberFormat;
import lombok.Builder;
import lombok.Data; import java.math.BigDecimal; @Data
@Builder
public class RespCustomerDailyImport { @ExcelProperty("客户编码")
private String customerName; @ExcelProperty("MIS编码")
private String misCode; @ExcelProperty("月度滚动额")
private BigDecimal monthlyQuota; @ExcelProperty("最新应收账款余额")
private BigDecimal accountReceivableQuota; @NumberFormat("#.##%")
@ExcelProperty("本月利率(年化)")
private BigDecimal dailyInterestRate;
}
package com.example.demo.excel.demo0;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.beust.jcommander.internal.Lists;
import com.example.demo.anoationselect.loginannoation.AuthLogin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List; @Controller
@RequestMapping
public class Export { @GetMapping("/export0")
@AuthLogin
public void export(HttpServletResponse response) throws IOException {
// 生成数据
List<RespCustomerDailyImport> respCustomerDailyImports = Lists.newArrayList();
for (int i = 0; i < 50; i++) {
RespCustomerDailyImport respCustomerDailyImport = RespCustomerDailyImport.builder()
.misCode(String.valueOf(i))
.customerName("customerName" + i)
.monthlyQuota(new BigDecimal(String.valueOf(i)))
.accountReceivableQuota(new BigDecimal(String.valueOf(i)))
.dailyInterestRate(new BigDecimal(String.valueOf(i))).build();
respCustomerDailyImports.add(respCustomerDailyImport);
} response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("导出", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), RespCustomerDailyImport.class)
.sheet("sheet0")
// 设置字段宽度为自动调整,不太精确
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.doWrite(respCustomerDailyImports);
}
}
导入:
package com.example.demo.excel.demo;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.util.StringUtils;
import com.beust.jcommander.internal.Lists; import java.util.List; /**
* 导入监听器
*/
public class CustomerDailyImportListener extends AnalysisEventListener {
List misCodes= Lists.newArrayList(); @Override
public void invoke(Object data, AnalysisContext context) {
String misCode = ((ReqCustomerDailyImport) data).getMisCode();
if (StringUtils.isEmpty(misCode)) {
throw new RuntimeException(String.format("第%s行MIS编码为空,请核实", context.readRowHolder().getRowIndex() + 1));
}
if (misCodes.contains(misCodes)) {
throw new RuntimeException(String.format("第%s行MIS编码已重复,请核实", context.readRowHolder().getRowIndex() + 1));
} else {
misCodes.add(misCode);
}
} @Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
misCodes.clear();
} @Override
public void onException(Exception exception, AnalysisContext context) throws Exception {
// ExcelDataConvertException:当数据转换异常的时候,会抛出该异常,此处可以得知第几行,第几列的数据
if (exception instanceof ExcelDataConvertException) {
Integer columnIndex = ((ExcelDataConvertException) exception).getColumnIndex() + 1;
Integer rowIndex = ((ExcelDataConvertException) exception).getRowIndex() + 1;
String message = "第" + rowIndex + "行,第" + columnIndex + "列" + "数据格式有误,请核实";
throw new RuntimeException(message);
} else if (exception instanceof RuntimeException) {
throw exception;
} else {
super.onException(exception, context);
}
} }
package com.example.demo.excel.demo;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data; import java.math.BigDecimal; /**
*导入测试实体
*/
@Data
public class ReqCustomerDailyImport { @ExcelProperty(index = 0)
private String customerName; /**
* MIS编码
*/
@ExcelProperty(index = 1)
private String misCode; /**
* 月度滚动额
*/
@ExcelProperty(index = 3)
private BigDecimal monthlyQuota; /**
* 最新应收账款余额
*/
@ExcelProperty(index = 4)
private BigDecimal accountReceivableQuota; /**
* 本月利率(年化)
*/
@ExcelProperty(index = 5)
private BigDecimal dailyInterestRate; }
package com.example.demo.excel.demo;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty; /**
* 类型转换器
*/
public class StringConverter implements Converter<String> { @Override
public Class supportJavaTypeKey() {
return String.class;
} @Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
} /**
* 将excel对象转成Java对象,这里读的时候会调用
*
* @param cellData NotNull
* @param contentProperty Nullable
* @param globalConfiguration NotNull
* @return
*/
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return "自定义:" + cellData.getStringValue();
} /**
* 将Java对象转成String对象,写出的时候调用
* @param value
* @param contentProperty
* @param globalConfiguration
* @return
*/
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData(value);
} }
package com.example.demo.excel.demo;

import com.alibaba.excel.EasyExcel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; import java.io.IOException;
import java.io.InputStream;
import java.util.List; /**
* 导入测试
*/
@Controller
@RequestMapping
public class Qwert { @PostMapping("/import")
public void importCustomerDaily(@RequestParam MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
List<ReqCustomerDailyImport> reqCustomerDailyImports = EasyExcel.read(inputStream)
.head(ReqCustomerDailyImport.class)
// 设置sheet,默认读取第一个
.sheet()
// 设置标题所在行数
.headRowNumber(2)
.doReadSync(); } @PostMapping("/import0") public void get(@RequestParam MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
List<ReqCustomerDailyImport> reqCustomerDailyImports = EasyExcel.read(inputStream)
// 这个转换是成全局的, 所有java为string,excel为string的都会用这个转换器。
// 如果就想单个字段使用请使用@ExcelProperty 指定converter
.registerConverter(new StringConverter())
// 注册监听器,可以在这里校验字段
.registerReadListener(new CustomerDailyImportListener())
.head(ReqCustomerDailyImport.class)
.sheet()
.headRowNumber(2)
.doReadSync();
}
}

easyexcel的更多相关文章

  1. 阿里巴巴excel工具easyexcel 助你快速简单避免OOM

    Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有 ...

  2. easyExcel导出excel的简单使用

    easyExcel导出excel的简单使用 Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定 ...

  3. 阿里 EasyExcel 使用及避坑

    github地址:https://github.com/alibaba/easyexcel 原本在项目中使用EasyPoi读取excel,后来为了统一技术方案,改用阿里的EasyExcel.EasyE ...

  4. EasyExcel导入工具(SpringMVC下使用)

    easyExcel:由阿里巴巴公司开发,由github托管 github上有详细使用文档 github地址:https://github.com/alibaba/easyexcel/blob/mast ...

  5. 阿里 EasyExcel 7 行代码优雅地实现 Excel 文件生成&下载功能

    欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 个人网站: https://www.ex ...

  6. Excel解析easyexcel工具类

    Excel解析easyexcel工具类 easyexcel解决POI解析Excel出现OOM <!-- https://mvnrepository.com/artifact/com.alibab ...

  7. easyexcel 读写测试

    <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId> ...

  8. EasyExcel 轻松灵活读取Excel内容

    写在前面 Java 后端程序员应该会遇到读取 Excel 信息到 DB 等相关需求,脑海中可能突然间想起 Apache POI 这个技术解决方案,但是当 Excel 的数据量非常大的时候,你也许发现, ...

  9. 【软件工具】easyExcel简明使用指南

    easyExcel简介 Java领域解析.生成Excel比较有名的框架有Apache poi.jxl等.但他们都存在一个严重的问题就是非常的耗内存.如果你的系统并发量不发的话可能还行,但是一旦并发上来 ...

  10. Excel映射到实体-easyexcel工具

    来源 项目需要把Excel进行解析,并映射到对象属性,实现类似Mybatis的ORM的效果.使用的方式是自定义注解+POI,这种方式代码复杂而且不易于维护. easyexcel是阿里巴巴开源的一个框架 ...

随机推荐

  1. 国产深度学习框架mindspore-1.3.0 gpu版本无法进行源码编译

    官网地址: https://www.mindspore.cn/install 所有依赖环境 进行sudo make install 安装,最终报错: 错误记录信息: cat     /tmp/mind ...

  2. Jmeter入门 浏览器设置代理服务器和录制脚本

    第一步: 可以设置浏览器代理,本文章推荐使用火狐浏览器 在浏览器-首选项--网络设置里面设置代理服务器 注意:端口号可以自行设置,但是不可以与本机其他代理产生冲突 第二步: 打开jmeter工具,添加 ...

  3. Xshell记录Linux连接操作日志遇到的坑

    1.问题描述: 在Windows上,以前一直使用Secure CRT连接Linux主机进行远程操作,使用CRT的日志功能记录连接过程中的所有操作以及输出. 最近(2019-8-17)使用Xshell进 ...

  4. javascript学习(五)之标准对象

    一.RegExp:正则表达式是一种用来匹配字符串的强有力的武器.它的设计思想是用一种描述性的语言来给字符串定义一个规则, 凡是符合规则的字符串,我们就认为它"匹配"了,否则,该字符 ...

  5. JS 之循环 应用案例1

    应用场景:将el-select下拉框的lab值,显示在下面的详情text框,见下图 用到了 el-select 传值,js循环判断options.code是否等于传进来的值,等于就break; tex ...

  6. HttpRunner3源码阅读:2. 模型定义

    models.py 昨天体验的时候我们分别执行了httprunner -h,httprunner startproject demo, httprunner run demo,但是源码中其调用了其他文 ...

  7. 2021qwb [强网先锋]赌徒 Writeup + 环境复现

    2021 qwb [强网先锋]赌徒 Writeup + 环境复现(win10) 1.本地环境复现(win10+phpStudy2018) 将比赛文件复制到phpStudy的\phpStudy\PHPT ...

  8. 关于MySQL8的WITH查询学习

    目录 前言 示例 练习 总结 前言 对于逻辑复杂的sql,with可以大大减少临时表的数量,提升代码的可读性.可维护性 MySQL 8.0终于开始支持with语句了,对于复杂查询,可以不用写那么多的临 ...

  9. ICCV2021 | 重新思考视觉transformers的空间维度

    ​ 论文:Rethinking Spatial Dimensions of Vision Transformers 代码:https://github.com/naver-ai/pit 获取:在CV技 ...

  10. kubernetes/k8s CRI分析-kubelet创建pod分析

    先来简单回顾上一篇博客<kubernetes/k8s CRI 分析-容器运行时接口分析>的内容. 上篇博文先对 CRI 做了介绍,然后对 kubelet CRI 相关源码包括 kubele ...