导出:

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. PAT甲级:1036 Boys vs Girls (25分)

    PAT甲级:1036 Boys vs Girls (25分) 题干 This time you are asked to tell the difference between the lowest ...

  2. 每天五分钟Go - 循环语句

    带条件的for循环 for init; condition; post { } 示例代码 for i:=0;i<10;i++{ fmt.Println("current:", ...

  3. POJ3667 Hotel 题解

    和最大子段和的思路是一样的,可以记 \(lmax,rmax,dat\) 分别表示从当前区间最靠左/右的最大连续空子段和当前区间的最大连续空子段. 需要用延迟标记,每次遇到开房操作先ask,如果能找到就 ...

  4. NumPy之:多维数组中的线性代数

    目录 简介 图形加载和说明 图形的灰度 灰度图像的压缩 原始图像的压缩 总结 简介 本文将会以图表的形式为大家讲解怎么在NumPy中进行多维数据的线性代数运算. 多维数据的线性代数通常被用在图像处理的 ...

  5. python安装pyeda库--windows版

    本页介绍了如何购买自己的PyEDA闪亮副本.PyEDA项目的主要目标是成为主流的Python软件包,并遵守社区中遵守的大多数约定. 支持平台 PyEDA支持Windows以及任何带有C编译器的平台.作 ...

  6. Python自动化测试面试题-经验篇

    目录 Python自动化测试面试题-经验篇 Python自动化测试面试题-用例设计篇 Python自动化测试面试题-Linux篇 Python自动化测试面试题-MySQL篇 Python自动化测试面试 ...

  7. 搭建NodeJS开发环境

    Windows10下搭建NodeJS开发环境 ======================================== 下载 NodeJS 安装包,最好使用LTS长期支持正式版 下载见 如下链 ...

  8. 第十八篇 -- QTreeWidget应用篇 -- kuwo

    效果图: 最近学习QTreeWidget,总想着做些什么,正好学习过一点简单的爬虫,就做了一个简易的"酷我音乐下载器",界面可能不太好看,以后继续优化. ui_kuwo.py # ...

  9. Bootstrap 树形列表与右键菜单

    Bootstrap 树形列表与右键菜单 介绍两个Bootstrap的扩展 Bootstrap Tree View 树形列表 jQuery contextMenu 右键菜单 Demo采用CDN分发,直接 ...

  10. 微软内推常见问题 Q&A

    很高兴,已经成功内推 59 人拿到了微软 offer! 两年前,我就已经写过一篇微软面经,帮助到了不少人: 微软面经分享:如何更好地做好面试准备 在这两年的内推过程中,往往会有不少候选人来问我有关微软 ...