欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > easyexcel快速使用

easyexcel快速使用

2025/2/21 0:47:10 来源:https://blog.csdn.net/weixin_51635918/article/details/145637666  浏览:    关键词:easyexcel快速使用

1.easyexcel

EasyExcel是一个基于ava的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel

即通过java完成对excel的读写操作,        上传下载

2.easyexcel写操作

把java类中的对象写入到excel表格中

步骤

1.引入依赖

<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>4.0.0</version>
</dependency>
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><!-- 这个版本可以继续往上升 ,但是不要低于这个 --><version>2.15.0</version>
</dependency>

2.封装相应的对象

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExcelDemo {@ExcelProperty(value = "姓名")private String name;@ExcelProperty(value = "年龄")private Integer age;@ExcelProperty(value = "性别")private String sex;//标记该属性不写入exccel表格中@ExcelIgnoreprivate String address;
}

3.通过easyexcel写入

测试类

package com.ghx;import com.alibaba.excel.EasyExcel;
import com.ghx.excel.ExcelDemo;import java.util.ArrayList;
import java.util.List;/*** @author :guo* @date :Created in 2025/2/14 17:19* @description:* @version:*/
public class TestWriterDemo {public static void main(String[] args) {//fileName:excel文件所在的路径及名称String fileName = "D:\\AAAAAA\\javamaven\\boot\\demoeasy\\easyExcel01.xlsx";List<ExcelDemo> data=new ArrayList<>();data.add(new ExcelDemo("小明", 18, "男", "北京"));data.add(new ExcelDemo("小李", 19, "女", "上海"));data.add(new ExcelDemo("小刚", 20, "男", "深圳"));data.add(new ExcelDemo("小文", 21, "女", "广州"));// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭EasyExcel.write(fileName, ExcelDemo.class).sheet("测试1").doWrite(data);}
}

web端

package com.ghx.controller;import com.alibaba.excel.EasyExcel;
import com.ghx.excel.ExcelDemo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;/*** @author :guo* @date :Created in 2025/2/14 20:01* @description:* @version:*/
@Controller
public class ExcelController {@GetMapping("download")public void download(HttpServletResponse response) throws IOException {// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postmanresponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系String fileName = URLEncoder.encode("web测试", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");List<ExcelDemo> data=new ArrayList<>();data.add(new ExcelDemo("小明", 18, "男", "北京"));data.add(new ExcelDemo("小李", 19, "女", "上海"));data.add(new ExcelDemo("小刚", 20, "男", "深圳"));data.add(new ExcelDemo("小文", 21, "女", "广州"));EasyExcel.write(response.getOutputStream(), ExcelDemo.class).sheet("模板").doWrite(data);}
}

3.easyexcel读操作

1.监听器

package com.ghx.excel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.ghx.excel.DemoDAO;
import com.ghx.excel.ExcelDemo;
import lombok.extern.slf4j.Slf4j;import java.util.List;// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
@Slf4j
public class DemoDataListener implements ReadListener<ExcelDemo> {/*** 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收*/private static final int BATCH_COUNT = 100;/*** 缓存的数据*/private List<ExcelDemo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);/*** 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。*/private DemoDAO demoDAO;public DemoDataListener() {// 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数demoDAO = new DemoDAO();}/*** 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来** @param demoDAO*/public DemoDataListener(DemoDAO demoDAO) {this.demoDAO = demoDAO;}/*** 这个每一条数据解析都会来调用** @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}* @param context*/@Overridepublic void invoke(ExcelDemo data, AnalysisContext context) {System.out.println("解析到一条数据:{}"+JSON.toJSONString(data));cachedDataList.add(data);// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOMif (cachedDataList.size() >= BATCH_COUNT) {saveData();// 存储完成清理 listcachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);}}/*** 所有数据解析完成了 都会来调用** @param context 最后执行的代码*/@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {// 这里也要保存数据,确保最后遗留的数据也存储到数据库saveData();System.out.println("所有数据解析完成!");}/*** 加上存储数据库*/private void saveData() {System.out.println("{}条数据,开始存储数据库!"+cachedDataList.size());demoDAO.save(cachedDataList);System.out.println("存储数据库成功!");}
}

2.

package com.ghx.excel;import java.util.List;/*** 假设这个是你的DAO存储。当然还要这个类让spring管理,当然你不用需要存储,也不需要这个类。**/
@Component
public class DemoDAO {public void save(List<ExcelDemo> list) {// 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入}
}

3.测试

package com.ghx;import com.alibaba.excel.EasyExcel;
import com.ghx.excel.DemoDataListener;
import com.ghx.excel.ExcelDemo;/*** @author :guo* @date :Created in 2025/2/14 20:24* @description:* @version:*/
public class TestReadDemo {public static void main(String[] args) {String fileName = "D:\\AAAAAA\\javamaven\\boot\\demoeasy\\easyExcel01.xlsx";// 这里默认读取第一个sheetEasyExcel.read(fileName, ExcelDemo.class, new DemoDataListener()).sheet().doRead();}
}

 web版

1.文件上传依赖

<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.5</version>
</dependency>

2.controller
 

package com.ghx.controller;import com.alibaba.excel.EasyExcel;
import com.ghx.excel.DemoDAO;
import com.ghx.excel.DemoDataListener;
import com.ghx.excel.ExcelDemo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;/*** @author :guo* @date :Created in 2025/2/14 20:01* @description:* @version:*/
@Controller
public class ExcelController {@Autowiredprivate DemoDAO demoDAO;@GetMapping("download")public void download(HttpServletResponse response) throws IOException {// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postmanresponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系String fileName = URLEncoder.encode("web测试", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");List<ExcelDemo> data=new ArrayList<>();data.add(new ExcelDemo("小明", 18, "男", "北京"));data.add(new ExcelDemo("小李", 19, "女", "上海"));data.add(new ExcelDemo("小刚", 20, "男", "深圳"));data.add(new ExcelDemo("小文", 21, "女", "广州"));EasyExcel.write(response.getOutputStream(), ExcelDemo.class).sheet("模板").doWrite(data);}@PostMapping("upload")@ResponseBodypublic String upload(MultipartFile file) throws IOException {EasyExcel.read(file.getInputStream(), ExcelDemo.class, new DemoDataListener(demoDAO)).sheet().doRead();return "success";}
}

测试

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词