导出:

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. Unittest方法 -- 测试套件

    TestSuite 测试固件 一. import unittestclass F6(unittest.TestCase): def setUp(self): pass def tearDown(sel ...

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

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

  3. RHEL7配置端口转发和地址伪装

    说明:这里是Linux服务综合搭建文章的一部分,本文可以作为Linux上使用firewalld做端口转发和地址伪装以及外网访问内网的参考. 注意:这里所有的标题都是根据主要的文章(Linux基础服务搭 ...

  4. Bootstrap框架--DataTables列表示例--添加判断

    一.参考代码 <%@ include file="./include/header.jsp"%> <!-- jquery.dataTables.css --> ...

  5. js中==和===的区别以及总结

    js中==和===的区别以及总结 学习js时我们会遇到 == 和 === 两种符号,现做总结如下 两种符号的定义 "==" 叫做相等运算符 "===" 叫做严格 ...

  6. 关于intouch/ifix嵌入视频控件并使用(海康,大华)

    2017年下半年项目开始接触利用intouch工控软件来进行项目二次开发.其中关于驱动的问题始终是上位机的重中之重,暂且不表(嘿嘿--),首先遇到的问题就是在弹窗中嵌入视频控件,监控设备的开停状态.经 ...

  7. Python小白的数学建模课-12.非线性规划

    非线性规划是指目标函数或约束条件中包含非线性函数的规划问题,实际就是非线性最优化问题. 从线性规划到非线性规划,不仅是数学方法的差异,更是解决问题的思想方法的转变. 非线性规划问题没有统一的通用方法, ...

  8. 【算法学习笔记】动态规划与数据结构的结合,在树上做DP

    前置芝士:Here 本文是基于 OI wiki 上的文章加以修改完成,感谢社区的转载支持和其他方面的支持 树形 DP,即在树上进行的 DP.由于树固有的递归性质,树形 DP 一般都是递归进行的. 基础 ...

  9. 获取元素在页面中位置 getBoundingClientRect()

    DOM 原生方法getBoundingClientRect()获取元素相对视口位置 DOMRect 对象包含了一组用于描述边框的只读属性--left.top.right和bottom,单位为像素.除了 ...

  10. JAVA基础语法:函数(方法)、类和对象(转载)

    4.JAVA基础语法:函数(方法).类和对象 函数 在java中函数也称为方法,是一段具备某种功能的可重用代码块. 一个函数包括这几部分: 函数头 函数头包括函数访问修饰符,函数返回值类型, 函数名, ...