- 浏览: 189456 次
- 性别:
- 来自: 北京
-
文章分类
- 全部博客 (228)
- 链接数据库 (1)
- Linux下面安装tomcat步骤 (1)
- 数据库简单添加索引 (1)
- Ubuntu 16.04安装jdk步骤 (1)
- Ubuntu 16.04安装mysql链接工具workbench (1)
- Java基础 (1)
- Java 获取两个时间的时间查 如 1 天 2 小时 30 分钟 (1)
- jdbc链接增删该查 (1)
- springboot 跨域解决 (1)
- springboot如何读取配置文件(application.yml)中的属性值 (1)
- springboot配置redis (1)
- 数据库访问优化法则 (1)
- springboot 配置定时任务 (1)
- 使用Spring Boot上传文件 (1)
- Java并发编程:Callable、Future和FutureTask (1)
- springboot配置所有信息demo (1)
- 常用软件地址 (1)
- Java DateUtil时间大全 (1)
- Java DateUtil当天,本周,本月时间获取方法 (1)
- @Data的用法 (1)
- 身份证工具类 (1)
- springboot添加日志 (1)
- List集合中的对象按照某个字段去重实现 (1)
- JavaBean和Map转换封装类 (1)
- StringUtils工具类用法 (1)
- BigDecimal用户详情 (1)
- java常用集合总结 (1)
- openfile 插件开发步骤 (0)
- Linux rpc客户端步骤 (1)
- Java开发必会的Linux命令 (1)
- springboot配置拦截器,控制登录跳转 (1)
- springboot 异步调用的方法 (0)
- springboot如何读取配置文件test.properties (1)
- springboot 异步调用的方法 (1)
- HttpClient操作,HttpPost (1)
- HttpGet (1)
- HttpDelete (1)
- HttpPut (1)
- mybatis生成代码后,想用自己的关联查询demo (1)
- Arrays工具类十大常用方法 (1)
- 如何生成唯一订单号 (1)
- 订单号唯一性 (1)
- msyql lest的用法 (1)
- //循环递归删除 (0)
- 循环递归删除 (1)
- java 属性首字母大写返回json解决办法 (1)
- 根据两点间经纬度坐标(double值),计算两点间距离,单位为米 (1)
- 运用开发好的jar部署到linux服务中 (1)
- mybatis批量新增 (1)
- mybatis 增删该查demo,新手必看 (1)
- java中字符串查找一个字符串的个数几种方法 (1)
- @Select in 的用法 (1)
- Ubuntu 16.04使用ieda简单配置 (1)
- 统计一个字符串中相应字符出现的次数 (1)
- SimpleDateFormat同步的解决办法 (1)
- gradle打包springboot jar例子 (1)
- java 提取字符串中的数字 (1)
- springboot 对像异常处理,还可以作为全部异常处理 (1)
- 面试题 (0)
- Linux下面安装virtualBox (1)
- java带有效期的map (1)
- 2018年JAVA基础面试题和高级面试题总结 (1)
- mysql修改密码的方法 (1)
- 排名前 16 的 Java 工具类 (1)
- 最完整的Linux常用命令大全 (1)
- Mysql 开发标准规范 (1)
- idea 快捷键 (1)
- mysql 建立索引 (1)
- Java中判断字符串是否为数字的五种方法 (1)
- springboot集成redis (1)
- springboot异步调用demo (1)
- springboot2集成redis (1)
- springboot2集成Elasticsearch (1)
- java过滤敏感字体的方式 (1)
- 对象的值赋给另一个对象 (1)
- mybitse+pagehelper 的使用方法 (1)
- java时间的处理 (1)
- xshell5 下载地址 (1)
- springboot2集成Excel (1)
- 检查数组是否包含某个值的方法 (1)
- 关于Java代码优化的N条建议! (1)
- Java Map按Key值进行排序 (1)
- List进行排序 (1)
- Stream 完整实例 (1)
- StringUtils isNoneBlank和isAnyBlank——demo (1)
- vim最全常用命令 (1)
- JWT生成Token (1)
- 学习参看地址 (1)
- java初始化数据 (1)
- 简单json (1)
- 数据库脚本 (1)
- restTemplate http请求 (1)
- 学习网站 (1)
- JsonUtil (1)
- Rsa (1)
- BeanUtils的赋值方法比较 (1)
- HttpClientUtil (2)
- ValidUtils (0)
- 读取excel,批量插入库demo (1)
- springboot对redis封装使用 (1)
- java后端简答验证码 (1)
- java高级面试题及其答案 (1)
- 序列换成json时 (1)
- 将所有的long变成string (1)
- ControllerAdvice (0)
- RedisService 工具类 (1)
- Java常用正则表达式验证工具类RegexUtils (1)
- CollectionUtil (1)
- thrift使用 (1)
- springboot播客学习 (1)
- mybitse 批量更新 (1)
- https://www.cnblogs.com/cxiaocai/p/11715874.html (1)
- elasticsearch安装及其head步骤 (0)
- elasticsearch7.6.2安装及其head、kibana、ik分词器步骤 (0)
- elasticsearch7.6.2集成springboot (0)
- gradle仓库选址 (1)
- elasticsearch7.6.2集成springboot2.2.6---2 (1)
- elasticsearch7.6.2安装及其head、kibana、ik分词器步骤-----1 (1)
- elasticsearch7.6.2集成springboot2.2.6基本语法---3 (1)
- Jsoup (1)
- elasticsearch7.6.2集成springboot2.2.6----demo (1)
- mybatis官网地址 (1)
- springboot发送邮件到qq (1)
- navicat Premium 链接sql Server的方法 (1)
- 简单开发springboot搭建 (1)
- sqlServer 查询两个小时的sql语句 (1)
- BigDecimalUtil (1)
- 雪花算法生成id (1)
- JsonUtils (1)
- Spring Boot监控与管理的实现 (1)
- springboot 使用undertow启动,替换tomcat (1)
- RedisConfig配置使用 (1)
- RedisUtil (1)
- easypoi读取excel (1)
- easyexcel读取excel (0)
- easyexcel读取excel与下载 (1)
- 生成指定长度的随机数 (1)
- Spring Boot AOP实战 (1)
- fastjsonfastjson新手必看 (1)
- 获取IP地址 (1)
- CommonUtils (1)
- 5万字长文:Stream和Lambda表达式最佳实践-附PDF下载 (1)
- DateUtils 最新工具类 (1)
- screw的使用 (1)
- 15000 字的 SQL 语句大全 (1)
- hutool (1)
- PdfToWord (1)
- MySQL修改最大连接数 (1)
- MAP排序 (1)
- 归纳从文件中读取数据的六种方法-JAVA IO基础总结 (1)
- 天气 (1)
- Intellij IDEA中Mybatis Mapper自动注入警告的6种解决方案 (1)
- 全网最全编程学习网站汇总来了,还不赶快收藏 (1)
- win10 (0)
- 电脑知识 (0)
- util工具类 (1)
- ieda提示mapper报错 (1)
- zysnba (1)
- 自增方式 (1)
- mybits链表查询 (1)
- SpringBoot如何优雅的处理校验参数 (1)
- 参考记录 (1)
- 企业微信封装方法 (1)
- 二维码 (1)
- mysql简单创建索引 (1)
- msyql函数 (1)
- mybitse-plus多表查询demo (1)
- git 提交本地代码步骤 (1)
- gradle5.X以上lombok引入 (1)
- SpringBoot定时任务及Cron表达式详解 (1)
- Hutool工具集之DateUtil(日期时间工具)详解使用 (1)
- 对象属性为空字符串变成null (1)
- DateUtils 工具类 (0)
- face++照片不对工具类 (1)
- 判断某个值是否在list集合中的某个对象中存在 (1)
- mybatisplus时间更新操作 (1)
- Java8 List通用方法处理总结 (1)
- 阿斯蒂芬 (0)
- springboot多数据源配置 (0)
- MyBatis和MyBatis-Plus 官网地址 (1)
- jwt (0)
- java---ValidUtils (1)
- Java之下载网络图片到本地文件夹 (1)
- 初始化内容数据 (1)
- springboot启动指定端口和启动环境 (1)
- 根据生日计算年龄 (1)
- idea快捷键大全 (1)
- springboot数据验证例子 (1)
- springboot文章 (1)
- 获取当前时间,推迟一年 (0)
- 获取当前时间,推迟一周 推迟一年示例 (1)
- ResultBean返回对象 (1)
- SpringBoot注解最全详解 (1)
- JeecgBoot (1)
- 电脑优化 (0)
- 简单数据队列 (1)
- CacheUtil换成工具类 (0)
- CacheUtil缓存工具类 (0)
- xml和对象互转 (0)
- 导出word (0)
- 企业微信通过code获取用户基本信息 (1)
- Java开发中的一些小技巧 (1)
- 判断当前时间是否在一个时间区间例如8点:21点 (1)
- springboot 启动指定环境 (1)
- 打印springboot启动的环境 (1)
- 根据时间日期获取当天是周几 (1)
- LocalDateTimeToString (1)
- java导出word (1)
- java 对xml和对象互转 (1)
- java CacheUtil缓存工具类 (1)
- 史上最牛逼电脑优化,让电脑飞起来 (1)
- isEmpty 和 isBlank 的用法区别 (1)
- 根据图片url地址获取其流InputStream (1)
- springboot解决LocalDateTime (1)
- springboot配置文件list映射 (1)
- SpringBoot中必须掌握的45个注解 (1)
- sql 优化的 15 个小技巧 (1)
- Cron表达式 (1)
- 数据库创建时间和修改时间默认值 (1)
- 小程序解析手机号 (1)
- 小程序获取手机号 (0)
- java 获取resource下面的文件路径,springboot打成jar也可以使用 (1)
- 数据库字段不显示对象和swwager前段不显示 (1)
- java生成pdf (1)
- springboot 异步调用 (1)
- java获取时间段内的每一天 (1)
- hutool----DateUtil简单的时间 (1)
- java 8两个List集合取交集、并集、差集、去重并集 (1)
- 服务调用demo (1)
- hutool导入excel (1)
- hutool导出 (1)
- 切面日志 (1)
- 校验参数为空 (1)
- 两个集合对象某一个属性相匹配 (1)
- JAVA stream流详细教程 (1)
- 查看java进程的命令 (1)
- Java 保留两位小数 百分数 (1)
- freemarker读写word模板生成word文档 (1)
- springboot项目中,读取 resources 目录下的文件的9种方式 (1)
- Knife4j (1)
- Java8 获取两个List交集 (1)
- list泛型和list对象交集 (1)
- 未来7天过生日的孩子sql (1)
- 数据校验,全局异常 (1)
- 获取最近10天过生日的sql (1)
- 随机数 (1)
- Java获取两个日期的天数打印 (1)
- 通过时间获取星期几 (1)
- Java时间类型相互转化 (2)
- 小程序登录 (1)
- 手机号 (0)
- sse调用 (0)
- httpsse调用 (1)
- 初始延迟3秒执行任务 (0)
最新评论
第一步导入相对应的jar
compile 'com.alibaba:fastjson:1.2.59'
implementation 'com.alibaba:easyexcel:1.1.2-beat1'
implementation 'org.projectlombok:lombok:1.18.2'
第二步建立对象
package com.example.springboot_excel.util;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @description:
* @author: chenmingjian
* @date: 19-3-18 16:16
*/
@Slf4j
public class ExcelUtil {
private static Sheet initSheet;
static {
initSheet = new Sheet(1, 0);
initSheet.setSheetName("sheet");
//设置自适应宽度
initSheet.setAutoWidth(Boolean.TRUE);
}
/**
* 读取少于1000行数据
* @param filePath 文件绝对路径
* @return
*/
public static List<Object> readLessThan1000Row(String filePath){
return readLessThan1000RowBySheet(filePath,null);
}
/**
* 读小于1000行数据, 带样式
* filePath 文件绝对路径
* initSheet :
* sheetNo: sheet页码,默认为1
* headLineMun: 从第几行开始读取数据,默认为0, 表示从第一行开始读取
* clazz: 返回数据List<Object> 中Object的类名
*/
public static List<Object> readLessThan1000RowBySheet(String filePath, Sheet sheet){
if(!StringUtils.hasText(filePath)){
return null;
}
sheet = sheet != null ? sheet : initSheet;
InputStream fileStream = null;
try {
fileStream = new FileInputStream(filePath);
return EasyExcelFactory.read(fileStream, sheet);
} catch (FileNotFoundException e) {
log.info("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(fileStream != null){
fileStream.close();
}
} catch (IOException e) {
log.info("excel文件读取失败, 失败原因:{}", e);
}
}
return null;
}
/**
* 读大于1000行数据
* @param filePath 文件觉得路径
* @return
*/
public static List<Object> readMoreThan1000Row(String filePath){
return readMoreThan1000RowBySheet(filePath,null);
}
/**
* 读大于1000行数据, 带样式
* @param filePath 文件觉得路径
* @return
*/
public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet){
if(!StringUtils.hasText(filePath)){
return null;
}
sheet = sheet != null ? sheet : initSheet;
InputStream fileStream = null;
try {
fileStream = new FileInputStream(filePath);
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(fileStream, sheet, excelListener);
return excelListener.getDatas();
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(fileStream != null){
fileStream.close();
}
} catch (IOException e) {
log.error("excel文件读取失败, 失败原因:{}", e);
}
}
return null;
}
/**
* 生成excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 数据源
* @param head 表头
*/
public static void writeBySimple(String filePath, List<List<Object>> data, List<String> head){
writeSimpleBySheet(filePath,data,head,null);
}
/**
* 生成excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 数据源
* @param sheet excle页面样式
* @param head 表头
*/
public static void writeSimpleBySheet(String filePath, List<List<Object>> data, List<String> head, Sheet sheet){
sheet = (sheet != null) ? sheet : initSheet;
if(head != null){
List<List<String>> list = new ArrayList<>();
head.forEach(h -> list.add(Collections.singletonList(h)));
sheet.setHead(list);
}
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
writer.write1(data,sheet);
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件导出失败, 失败原因:{}", e);
}
}
}
/**
* 生成excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 数据源
*/
public static void writeWithTemplate(String filePath, List<? extends BaseRowModel> data){
writeWithTemplateAndSheet(filePath,data,null);
}
/**
* 生成excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 数据源
* @param sheet excle页面样式
*/
public static void writeWithTemplateAndSheet(String filePath, List<? extends BaseRowModel> data, Sheet sheet){
if(CollectionUtils.isEmpty(data)){
return;
}
sheet = (sheet != null) ? sheet : initSheet;
sheet.setClazz(data.get(0).getClass());
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
writer.write(data,sheet);
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件导出失败, 失败原因:{}", e);
}
}
}
/**
* 生成多Sheet的excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param multipleSheelPropetys
*/
public static void writeWithMultipleSheel(String filePath,List<MultipleSheelPropety> multipleSheelPropetys){
if(CollectionUtils.isEmpty(multipleSheelPropetys)){
return;
}
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) {
Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet;
if(!CollectionUtils.isEmpty(multipleSheelPropety.getData())){
sheet.setClazz(multipleSheelPropety.getData().get(0).getClass());
}
writer.write(multipleSheelPropety.getData(), sheet);
}
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件导出失败, 失败原因:{}", e);
}
}
}
/*********************匿名内部类开始,可以提取出去******************************/
@Data
public static class MultipleSheelPropety{
private List<? extends BaseRowModel> data;
private Sheet sheet;
}
/**
* 解析监听器,
* 每解析一行会回调invoke()方法。
* 整个excel解析结束会执行doAfterAllAnalysed()方法
*
* @author: chenmingjian
* @date: 19-4-3 14:11
*/
@Getter
@Setter
public static class ExcelListener extends AnalysisEventListener {
private List<Object> datas = new ArrayList<>();
/**
* 逐行解析
* object : 当前行的数据
*/
@Override
public void invoke(Object object, AnalysisContext context) {
//当前行
// context.getCurrentRowNum()
if (object != null) {
datas.add(object);
}
}
/**
* 解析完所有数据后会调用该方法
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
//解析结束销毁不用的资源
}
}
/************************匿名内部类结束,可以提取出去***************************/
}
package com.example.springboot_excel.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
public class User extends BaseRowModel {
@ExcelProperty(value = "id", index = 0)
private Integer id;
@ExcelProperty(value = "name", index = 1)
private String name;
@ExcelProperty(value = "address", index = 2)
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第三步方法即可
@ApiOperation(value = "读取excel----file")
@PostMapping("/importExcel")
public String importExcel(@RequestParam("file") MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
//实例化实现了AnalysisEventListener接口的类
ExcelUtil.ExcelListener listener = new ExcelUtil.ExcelListener();
//传入参数
ExcelReader excelReader = new ExcelReader(inputStream, null, listener);
//读取信息
excelReader.read(new Sheet(1, 1, User.class));
//获取数据
List<Object> list = listener.getDatas();
List<User> catagoryList = new ArrayList<User>();
User catagory = new User();
//转换数据类型,并插入到数据库
for (int i = 0; i < list.size(); i++) {
catagory = (User) list.get(i);
System.out.println(catagory.getId()+"----"+catagory.getName()+"----"+catagory.getAddress());
}
return "ok";
}
下载
@GetMapping("/download")
@ApiOperation(value = "下载excel")
public void download(HttpServletResponse response) {
OutputStream out = null;
ExcelWriter writer = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
String date = sdf.format(new Date());
//通过查询组装数据
List<User> userlist = new ArrayList<>();
User user = new User();
user.setId(1);
user.setName("张三");
User user1 = new User();
user1.setId(2);
user1.setName("李四");
userlist.add(user);
userlist.add(user1);
//拼接导出的文件名
String fileName = date + new String(("告警数据").getBytes("UTF-8"), "ISO-8859-1") + ".xlsx";
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
//下载到浏览器默认地址
out = response.getOutputStream();
writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
Sheet sheet1 = new Sheet(1, 0, User.class);
sheet1.setSheetName("sheet1");
writer.write(userlist, sheet1);
userlist.clear();
} catch (Exception e) {
// log.error("告警信息下载失败"+e.getMessage(),e);
} finally {
try {
out.flush();
writer.finish();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
compile 'com.alibaba:fastjson:1.2.59'
implementation 'com.alibaba:easyexcel:1.1.2-beat1'
implementation 'org.projectlombok:lombok:1.18.2'
第二步建立对象
package com.example.springboot_excel.util;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @description:
* @author: chenmingjian
* @date: 19-3-18 16:16
*/
@Slf4j
public class ExcelUtil {
private static Sheet initSheet;
static {
initSheet = new Sheet(1, 0);
initSheet.setSheetName("sheet");
//设置自适应宽度
initSheet.setAutoWidth(Boolean.TRUE);
}
/**
* 读取少于1000行数据
* @param filePath 文件绝对路径
* @return
*/
public static List<Object> readLessThan1000Row(String filePath){
return readLessThan1000RowBySheet(filePath,null);
}
/**
* 读小于1000行数据, 带样式
* filePath 文件绝对路径
* initSheet :
* sheetNo: sheet页码,默认为1
* headLineMun: 从第几行开始读取数据,默认为0, 表示从第一行开始读取
* clazz: 返回数据List<Object> 中Object的类名
*/
public static List<Object> readLessThan1000RowBySheet(String filePath, Sheet sheet){
if(!StringUtils.hasText(filePath)){
return null;
}
sheet = sheet != null ? sheet : initSheet;
InputStream fileStream = null;
try {
fileStream = new FileInputStream(filePath);
return EasyExcelFactory.read(fileStream, sheet);
} catch (FileNotFoundException e) {
log.info("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(fileStream != null){
fileStream.close();
}
} catch (IOException e) {
log.info("excel文件读取失败, 失败原因:{}", e);
}
}
return null;
}
/**
* 读大于1000行数据
* @param filePath 文件觉得路径
* @return
*/
public static List<Object> readMoreThan1000Row(String filePath){
return readMoreThan1000RowBySheet(filePath,null);
}
/**
* 读大于1000行数据, 带样式
* @param filePath 文件觉得路径
* @return
*/
public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet){
if(!StringUtils.hasText(filePath)){
return null;
}
sheet = sheet != null ? sheet : initSheet;
InputStream fileStream = null;
try {
fileStream = new FileInputStream(filePath);
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(fileStream, sheet, excelListener);
return excelListener.getDatas();
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(fileStream != null){
fileStream.close();
}
} catch (IOException e) {
log.error("excel文件读取失败, 失败原因:{}", e);
}
}
return null;
}
/**
* 生成excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 数据源
* @param head 表头
*/
public static void writeBySimple(String filePath, List<List<Object>> data, List<String> head){
writeSimpleBySheet(filePath,data,head,null);
}
/**
* 生成excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 数据源
* @param sheet excle页面样式
* @param head 表头
*/
public static void writeSimpleBySheet(String filePath, List<List<Object>> data, List<String> head, Sheet sheet){
sheet = (sheet != null) ? sheet : initSheet;
if(head != null){
List<List<String>> list = new ArrayList<>();
head.forEach(h -> list.add(Collections.singletonList(h)));
sheet.setHead(list);
}
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
writer.write1(data,sheet);
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件导出失败, 失败原因:{}", e);
}
}
}
/**
* 生成excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 数据源
*/
public static void writeWithTemplate(String filePath, List<? extends BaseRowModel> data){
writeWithTemplateAndSheet(filePath,data,null);
}
/**
* 生成excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 数据源
* @param sheet excle页面样式
*/
public static void writeWithTemplateAndSheet(String filePath, List<? extends BaseRowModel> data, Sheet sheet){
if(CollectionUtils.isEmpty(data)){
return;
}
sheet = (sheet != null) ? sheet : initSheet;
sheet.setClazz(data.get(0).getClass());
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
writer.write(data,sheet);
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件导出失败, 失败原因:{}", e);
}
}
}
/**
* 生成多Sheet的excle
* @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param multipleSheelPropetys
*/
public static void writeWithMultipleSheel(String filePath,List<MultipleSheelPropety> multipleSheelPropetys){
if(CollectionUtils.isEmpty(multipleSheelPropetys)){
return;
}
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) {
Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet;
if(!CollectionUtils.isEmpty(multipleSheelPropety.getData())){
sheet.setClazz(multipleSheelPropety.getData().get(0).getClass());
}
writer.write(multipleSheelPropety.getData(), sheet);
}
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路径错误, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件导出失败, 失败原因:{}", e);
}
}
}
/*********************匿名内部类开始,可以提取出去******************************/
@Data
public static class MultipleSheelPropety{
private List<? extends BaseRowModel> data;
private Sheet sheet;
}
/**
* 解析监听器,
* 每解析一行会回调invoke()方法。
* 整个excel解析结束会执行doAfterAllAnalysed()方法
*
* @author: chenmingjian
* @date: 19-4-3 14:11
*/
@Getter
@Setter
public static class ExcelListener extends AnalysisEventListener {
private List<Object> datas = new ArrayList<>();
/**
* 逐行解析
* object : 当前行的数据
*/
@Override
public void invoke(Object object, AnalysisContext context) {
//当前行
// context.getCurrentRowNum()
if (object != null) {
datas.add(object);
}
}
/**
* 解析完所有数据后会调用该方法
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
//解析结束销毁不用的资源
}
}
/************************匿名内部类结束,可以提取出去***************************/
}
package com.example.springboot_excel.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
public class User extends BaseRowModel {
@ExcelProperty(value = "id", index = 0)
private Integer id;
@ExcelProperty(value = "name", index = 1)
private String name;
@ExcelProperty(value = "address", index = 2)
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第三步方法即可
@ApiOperation(value = "读取excel----file")
@PostMapping("/importExcel")
public String importExcel(@RequestParam("file") MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
//实例化实现了AnalysisEventListener接口的类
ExcelUtil.ExcelListener listener = new ExcelUtil.ExcelListener();
//传入参数
ExcelReader excelReader = new ExcelReader(inputStream, null, listener);
//读取信息
excelReader.read(new Sheet(1, 1, User.class));
//获取数据
List<Object> list = listener.getDatas();
List<User> catagoryList = new ArrayList<User>();
User catagory = new User();
//转换数据类型,并插入到数据库
for (int i = 0; i < list.size(); i++) {
catagory = (User) list.get(i);
System.out.println(catagory.getId()+"----"+catagory.getName()+"----"+catagory.getAddress());
}
return "ok";
}
下载
@GetMapping("/download")
@ApiOperation(value = "下载excel")
public void download(HttpServletResponse response) {
OutputStream out = null;
ExcelWriter writer = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
String date = sdf.format(new Date());
//通过查询组装数据
List<User> userlist = new ArrayList<>();
User user = new User();
user.setId(1);
user.setName("张三");
User user1 = new User();
user1.setId(2);
user1.setName("李四");
userlist.add(user);
userlist.add(user1);
//拼接导出的文件名
String fileName = date + new String(("告警数据").getBytes("UTF-8"), "ISO-8859-1") + ".xlsx";
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
//下载到浏览器默认地址
out = response.getOutputStream();
writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
Sheet sheet1 = new Sheet(1, 0, User.class);
sheet1.setSheetName("sheet1");
writer.write(userlist, sheet1);
userlist.clear();
} catch (Exception e) {
// log.error("告警信息下载失败"+e.getMessage(),e);
} finally {
try {
out.flush();
writer.finish();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
相关推荐
在读取Excel时,我们需要定义一个实体类,该类的属性对应Excel中的列,并且需要使用注解来指定字段的位置。同时,需要编写一个监听器,继承自EasyExcel的抽象类,重写`invoke`方法来处理每一行的数据。 写入Excel时...
在实际的应用中,我们经常要读取Excel的字段,比如一个医保中心程序生成的结算单是Excel格式的,我们需要读取Excel里面的内容,找到结算信息。最笨的办法就是一行一列的数,可是结算表含有很多的单元格合并的时候,...
3. **读取Excel**:调用EasyExcel.read()方法,传入文件路径和自定义的监听器,即可开始读取Excel数据。监听器中的方法会在读取到每一行数据时被调用。 4. **写入Excel**:使用EasyExcel.write()方法,传入输出流和...
Excel操作,读取及汇出,复杂表头,可以设置表头样式
- 配置Bean:创建一个`EasyExcelListener`监听器,用于处理读取Excel时的事件,如数据验证、错误处理等。 - 使用`@RestController`注解的Controller层方法,提供HTTP接口进行Excel的上传和下载。 3. **导入Excel*...
本文将深入探讨如何在Java环境中读取Excel格式(.xls或.xlsx)以及CSV(逗号分隔值)格式的文件,同时也会提及所给的压缩包文件中的相关资源。 首先,Excel文件是一种由Microsoft Office提供的电子表格格式,用于...
### 读取Excel文件将数据存入Map集合 在日常工作中,经常需要处理Excel文件,尤其是在数据统计、分析等场景中。本篇文章介绍了一个方法,该方法能够读取Excel文件并将其中的数据存储到Java中的`Map`集合里,便于...
EasyExcel支持读取和写入Excel文件,无需内存转换成List,这大大减少了内存消耗,特别是在处理大量数据时。此外,它还提供了简单的API,使得Excel操作变得简单易懂。 要将EasyExcel整合到SpringBoot项目中,首先...
本案例采用的poi读取大数据的excel文件 usermodel模式对excel操作前需要将文件全部转入内存,对较大文件来说内存开销很大。但是其使用简单。 eventusermodel模式采用事件模型,对文件边读取边处理,内存消耗较低,...
EasyExcel提供了一种多线程并发读取Excel数据的方式,通过`readSheetHandler`和`executeParallel`方法,可以将读取任务分配到多个线程中执行。每个线程独立处理一部分行数据,这样可以显著提升数据处理速度。 3. *...
通过自定义的DataReadListener,我们就可以在读取Excel的时候做处理。 每读取到一行数据会先做数据校验,如果校验通过后就会放到缓存集合中,List数量积累到1000时就会通过Mybatis的批量操作进行数据插入。...
在IT行业中,处理大量数据是常见的任务,而Excel由于其易用性和强大的表格管理功能,经常被用作数据存储和分析的工具。然而,当数据量达到百万级别时,使用默认的Excel操作方法可能会遇到性能瓶颈,导致读写速度极慢...
EasyExcel 作为一款卓越的 Java 语言编写的 Excel 处理利器,以其出色的性能和丰富的功能,能够轻松、高效地实现 Excel 文件的读写操作,极大地提升了开发效率。在此,我们将这些不可或缺的 Jar 包资源统一整理并...
结合PHPExcel插件写的读取excel文件内容,并返回二维数组。可以控制读取excel哪张工作表,读取几列的内容。
EasyExcel的核心设计理念是“按需加载”,即在读取Excel时只加载当前处理的数据行,极大地优化了内存使用。 在Spring Boot项目中集成EasyExcel,首先需要在`pom.xml`文件中添加依赖。EasyExcel的最新版本通常可以在...
1. **数据读取**:EasyExcel支持流式读取Excel,这意味着它可以在不加载整个文件到内存的情况下处理大型Excel文件,大大降低了内存消耗。通过`ExcelReaderBuilder`,你可以创建一个读取器,并设置监听器来处理读取到...
例如,在读取Excel数据时,我们可以通过实现`AnalysisEventListener`接口来自定义数据处理逻辑,然后使用`EasyExcel.read()`方法启动读取过程。在写入数据时,定义好对应的实体类,使用`EasyExcel.write()`方法即可...
2. **读取Excel**:调用`EasyExcel.read()`方法,传入Excel文件路径和监听器实例。例如: ```java EasyExcel.read("path_to_your_excel_file", YourDataModel.class, new YourListener()).sheet().doRead(); ``` ...
poi导入/导出Excel表格,合并单元格的读取和设置
3. 使用EasyExcel的`read()`方法读取Excel数据,传入文件路径和处理器实例。 4. 使用EasyExcel的`write()`方法写入Excel数据,传入OutputStream和实体类的Class对象。 四、性能优化 EasyExcel采用了流式处理,避免...