Java实现Excel百万级数据的导入(约30s完成)

2024-04-07 10:44

本文主要是介绍Java实现Excel百万级数据的导入(约30s完成),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

在遇到大数据量excel,50MB大小或数百万级别的数据读取时,使用常用的POI容易导致读取时内存溢出或者cpu飙升。
本文讨论的是针对xlsx格式的excel文件上传,采用com.monitorjbl.xlsx.StreamingReader 。

什么是StreamReader?
StreamReader 是 java.io 包中的一个类,用于读取字符流的高级类。它继承自 Reader 类,可以以字符为单位读取文件中的数据。
StreamReader的主要功能?

  • 以字符为单位读取文件中的数据
  • 提供了多种读取方法,如read()、readLine()等
  • 可以指定字符编码,以适应不同类型的文件

StreamReader的优势?

  • 简化了文件读取的过程,提供了高层次的读取方法可以处理不同类型的文件,如文本文件、CSV文件等
  • 可以读取大型文件,节省内存空间

注:StreamReader只能用遍历形式读取数据

        Sheet sheet = wk.getSheetAt(0);//遍历所有的行for (Row row : sheet) {System.out.println("开始遍历第" + row.getRowNum() + "行数据:");//遍历所有的列for (Cell cell : row) {System.out.print(cell.getStringCellValue() + " ");}System.out.println(" ");}

 

案例步骤

1、导入文件前端接口

Controller.java

    /*** 导入文件前端接口*/@PostMapping("/importData")@ResponseBodypublic AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {// 开始时间Long begin = new Date().getTime();// excel转换为List集合(约30s~40s)List<TpInstallationMaintenanceLabelDetailed> tpInstallationMaintenanceLabelDetailedList = largeFilesUtils.importExcelLargeFile(file, updateSupport);// 结束时间Long end = new Date().getTime();// 数据导入(约30s)String message = importInstallationMaintenanceLabelDetailed(tpInstallationMaintenanceLabelDetailedList, updateSupport);// 总用时(约60s~70s)message = message +"<br/>数据转换花费时间 : "+(end - begin) / 1000 + " s" ;// 返回return AjaxResult.success(message);}

2、Excel数据转为List

largeFilesUtils.java


import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import com.monitorjbl.xlsx.StreamingReader;
import com.ruoyi.huawei.domain.TpInstallationMaintenanceLabelDetailed;/*** 大文件Excel导入* * @author y* @date 2024-03-29*/
@Service
public class LargeFilesUtils {/*** 大文件Excel导入* * @param* @return 工具*/public List<TpInstallationMaintenanceLabelDetailed> importExcelLargeFile(MultipartFile file,boolean updateSupport) {List<TpInstallationMaintenanceLabelDetailed> tpInstallationMaintenanceLabelDetailedList = new ArrayList<TpInstallationMaintenanceLabelDetailed>();try {// 大文件测试开始InputStream inputStream = file.getInputStream();// com.monitorjbl.xlsx.StreamingReader Workbook workbook = StreamingReader.builder().rowCacheSize(1000) // 缓存到内存中的行数(默认是10).bufferSize(10240) // 读取资源时,缓存到内存的字节大小(默认是1024).open(inputStream);// 获取第一个ShhetSheet sheet = workbook.getSheetAt(0);//boolean fastRowBoolean = true;// monitorjbl只能支持遍历,不能通过指定下标获取for (Row row : sheet) {// 判断是否首行if(fastRowBoolean) {// 设置为非首行fastRowBoolean = false;// continue 语句用于跳过当前循环中剩余的代码,并开始下一次迭代。continue;}// 创建实体TpInstallationMaintenanceLabelDetailed rowData = new TpInstallationMaintenanceLabelDetailed();// 列下标初始化int n = 0;// 遍历列for (Cell cell : row) {//switch (n) {// 第一列case 0:rowData.setPppoeAccount(cell.getStringCellValue());break;// 第二列case 1:rowData.setInstallationMaintenanceName(cell.getStringCellValue());break;case 2:rowData.setCounty(cell.getStringCellValue());break;case 3:rowData.setPoorQualityUser(cell.getStringCellValue());break;case 4:rowData.setOldLightCat(cell.getStringCellValue());break;case 5:rowData.setSetTopBoxWirelessConnection(cell.getStringCellValue());break;case 6:rowData.setPleaseUseXgponOnu(cell.getStringCellValue());break;case 7:rowData.setHighTemperatureLightCat(cell.getStringCellValue());break;case 8:rowData.setAnOldSetTopBox(cell.getStringCellValue());break;case 9:rowData.setTwoOldSetTopBoxes(cell.getStringCellValue());break;case 10:rowData.setThreeOldSetTopBoxes(cell.getStringCellValue());break;case 11:rowData.setAnPoorQualityRouter(cell.getStringCellValue());break;case 12:rowData.setTwoPoorQualityRouters(cell.getStringCellValue());break;case 13:rowData.setThreePoorQualityRouters(cell.getStringCellValue());break;case 14:rowData.setThreeOrMoreLowQualityRouters(cell.getStringCellValue());break;case 15:rowData.setThreeOrMoreOldSetTopBoxes(cell.getStringCellValue());break;case 16:rowData.setSeverelyPoorQualityUsersAndOldOpticalCats(cell.getStringCellValue());break;// 处理其他属性default:break;}// 列下标+1n = n+1;}tpInstallationMaintenanceLabelDetailedList.add(rowData);}workbook.close();} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e);}return tpInstallationMaintenanceLabelDetailedList;}}

3、List集合数据导入

importInstallationMaintenanceLabelDetailed

/*** 导入文件分析*/public String importInstallationMaintenanceLabelDetailed(List<TpInstallationMaintenanceLabelDetailed> tpInstallationMaintenanceLabelDetailedList, Boolean isUpdateSupport){if (StringUtils.isNull(tpInstallationMaintenanceLabelDetailedList) || tpInstallationMaintenanceLabelDetailedList.size() == 0){throw new ServiceException("导入数据不能为空!");}// 执行开始时间Long begin = new Date().getTime();// 线程数final int THREAD_COUNT = 10;// 每个线程处理的数据量final int BATCH_SIZE = tpInstallationMaintenanceLabelDetailedList.size() / THREAD_COUNT;// ExecutorService是Java中对线程池定义的一个接口ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);// for (int i = 0; i < THREAD_COUNT; i++) {// List数据开始下标final int startIndex = i * BATCH_SIZE;// List数据结束下标final int endIndex = (i + 1) * BATCH_SIZE;// 线程池执行executor.submit(new Runnable() {public void run() {// 初始化数据库连接对象Connection conn = null;// 初始化预编译的 SQL 语句的对象PreparedStatement ps = null;try {// 获取连接conn =  DriverManager.getConnection("jdbc:mysql://localhost:3306/tool_platform_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&useSSL=false", "root", "123456");//获取连接// 设置自动提交模式,默认trueconn.setAutoCommit(false);// sql前缀String prefix = "INSERT INTO tp_label_detailed ("+ "account,"+ "maintenance_name,"+ "county,quality_user,"+ "light_cat,wireless_connection,"+ "xgpon_onu,"+ "light_cat,"+ "an_box,two_boxes,"+ "three_boxes,"+ "an_router,"+ "two_routers,"+ "three_routers,"+ "three_or_more_routers,"+ "three_or_more_boxes,"+ "severely_and_cats"+ ") VALUES ";// 创建预编译对象ps = conn.prepareStatement(prefix);// 保存sql后缀StringBuffer suffix = new StringBuffer();// 执行条数int number_of_cycles = 0;//for (int j = startIndex; j < endIndex; j++) {// 拼接sqlsuffix.append("("+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getPppoeAccount()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getInstallationMaintenanceName()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getCounty()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getPoorQualityUser()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getOldLightCat()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getSetTopBoxWirelessConnection()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getPleaseUseXgponOnu()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getHighTemperatureLightCat()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getAnOldSetTopBox()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getTwoOldSetTopBoxes()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getThreeOldSetTopBoxes()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getAnPoorQualityRouter()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getTwoPoorQualityRouters()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getThreePoorQualityRouters()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getThreeOrMoreLowQualityRouters()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getThreeOrMoreOldSetTopBoxes()+"',"+"'"+tpInstallationMaintenanceLabelDetailedList.get(j).getSeverelyPoorQualityUsersAndOldOpticalCats()+"'"+"),");   //拼接sqlnumber_of_cycles = number_of_cycles +1;}// sql拼接String sql = prefix + suffix.substring(0, suffix.length() - 1);// 添加预处理sqlps.addBatch(sql);// 执行语句ps.executeBatch();// 提交conn.commit();// 初始化拼接sqlsuffix.setLength(0);// 初始化条数number_of_cycles = 1;} catch (SQLException e) {e.printStackTrace();} finally {if (ps != null) {try {// 关闭psps.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {// 关闭数据库连接conn.close();} catch (SQLException e) {e.printStackTrace();}}}}});}//关闭线程池,不接受新任务,但会把已添加的任务执行完executor.shutdown();// 等待所有线程完成任务while (!executor.isTerminated()) {} System.out.println("完成");// 结束时间Long end = new Date().getTime();// 耗时logger.debug(tpInstallationMaintenanceLabelDetailedList.size()+"条数据插入花费时间 : " + (end - begin) / 1000 + " s");//return "数据导入成功!共 " + tpInstallationMaintenanceLabelDetailedList.size() + " 条!"+"<br/>数据导入花费时间 : "+(end - begin) / 1000 + " s" ;}

这篇关于Java实现Excel百万级数据的导入(约30s完成)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/882390

相关文章

批量导入txt数据到的redis过程

《批量导入txt数据到的redis过程》用户通过将Redis命令逐行写入txt文件,利用管道模式运行客户端,成功执行批量删除以Product*匹配的Key操作,提高了数据清理效率... 目录批量导入txt数据到Redisjs把redis命令按一条 一行写到txt中管道命令运行redis客户端成功了批量删除k

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.