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

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter