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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

关于数据埋点,你需要了解这些基本知识

产品汪每天都在和数据打交道,你知道数据来自哪里吗? 移动app端内的用户行为数据大多来自埋点,了解一些埋点知识,能和数据分析师、技术侃大山,参与到前期的数据采集,更重要是让最终的埋点数据能为我所用,否则可怜巴巴等上几个月是常有的事。   埋点类型 根据埋点方式,可以区分为: 手动埋点半自动埋点全自动埋点 秉承“任何事物都有两面性”的道理:自动程度高的,能解决通用统计,便于统一化管理,但个性化定