大批量数据导出csv,平替导出excel性能优化解决方案封装工具类

阿丹:

        有些业务逻辑需要在导出非常大量的数据,几百甚至几千万的数据这个时候再导出excel来对于性能都不是很友好,这个时候就需要替换实现思路来解决这个问题。

        本文章提供了两种解决的方案,也是两种从数据库中拿取数据的方式一种是原生的jdbc一种是使用mybatis来封装对象来完成的。

使用字符串数组的导出:

package com.lianlu.export.util;import org.apache.poi.ss.formula.functions.T;import java.io.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;/*** CSV导出工具类,用于将数据列表导出为CSV文件。*/
public class CSVExportUtil {/*** 导出CSV文件。** @param dataList          需要导出的内容,类型为字符串数组的列表。* @param validationRulesMap 校验和替换规则的映射,键为列索引,值为一个映射,其中键为需要替换的字符串,值为替换后的字符串。* @param headers           CSV文件的表头,类型为字符串数组。* @param fileName          导出CSV文件的名称。* @throws IOException 如果在写入文件过程中发生异常。*/public static void exportCSV(List<String[]> dataList, Map<Integer, Map<String, String>> validationRulesMap, String[] headers, String fileName) throws IOException {// 预处理数据(校验和替换)List<String[]> preprocessedDataList = preprocessData(dataList, validationRulesMap);// 写入CSV文件writeCSVToFile(preprocessedDataList, headers, fileName);}/*** 不需要替换规则的导出* @param dataList* @param headers* @param fileName* @throws IOException*/public static void exportCSV(List<String[]> dataList, String[] headers, String fileName) throws IOException {// 写入CSV文件writeCSVToFile(dataList, headers, fileName);}/*** 预处理数据列表(校验和替换)。** @param dataList          原始数据列表。* @param validationRulesMap 校验和替换规则的映射。* @return 预处理后的数据列表。*/private static List<String[]> preprocessData(List<String[]> dataList, Map<Integer, Map<String, String>> validationRulesMap) {return dataList.stream().map(row -> preprocessDataRow(row, validationRulesMap)).collect(Collectors.toList());}/*** 预处理单行数据(校验和替换)。** @param row               单行数据。* @param validationRulesMap 校验和替换规则的映射。* @return 预处理后的单行数据。*/private static String[] preprocessDataRow(String[] row, Map<Integer, Map<String, String>> validationRulesMap) {for (Map.Entry<Integer, Map<String, String>> entry : validationRulesMap.entrySet()) {int columnIndex = entry.getKey();Map<String, String> rules = entry.getValue();String originalValue = row[columnIndex];String replacedValue = rules.getOrDefault(originalValue, originalValue);row[columnIndex] = replacedValue;}return row;}/*** 将预处理后的数据写入CSV文件。** @param dataList   预处理后的数据列表。* @param headers    CSV文件的表头。* @param fileName   导出CSV文件的名称。* @throws IOException 如果在写入文件过程中发生异常。*/private static void writeCSVToFile(List<String[]> dataList, String[] headers, String fileName) throws IOException {try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {// 写入表头writer.write(String.join(",", headers));writer.newLine();// 分批写入数据以提高性能AtomicInteger counter = new AtomicInteger(0);while (counter.get() < dataList.size()) {int batchSize = Math.min(10000, dataList.size() - counter.get()); // 每次写入10000条数据,可根据实际需求调整List<String[]> batchData = dataList.subList(counter.get(), counter.get() + batchSize);for (String[] dataRow : batchData) {writer.write(String.join(",", dataRow));writer.newLine();}counter.addAndGet(batchSize);}}}/*** 从泛型对象中获取属性值并转换为字符串数组。** @param data 泛型对象* @return 字符串数组,包含对象的属性值*/private String[] convertObjectToArray(T data) {Class<?> clazz = data.getClass();Field[] fields = clazz.getDeclaredFields();// 获取对象的所有字段,并设置它们为可访问for (Field field : fields) {field.setAccessible(true);}String[] rowData = new String[fields.length];// 遍历所有字段,获取每个字段的值并添加到字符串数组中for (int i = 0; i < fields.length; i++) {try {rowData[i] = fields[i].get(data).toString();} catch (IllegalAccessException e) {throw new RuntimeException("Failed to access field value", e);}}return rowData;}}

通过对象的导出:

package com.lianlu.export.util;import java.io.*;
import java.lang.reflect.Field;
import java.util.*;public class CSVExportUtil<T> {/*** 导出CSV文件。** @param dataList       需要导出的数据列表(泛型对象列表)* @param validationRulesMap 校验和替换规则映射(键为列索引,值为校验和替换规则的映射)* @param headers         CSV表头数组* @param fileName        导出CSV文件的名称* @throws IOException 如果在写入文件时发生错误*/public void exportCSV(List<T> dataList, Map<Integer, Map<String, String>> validationRulesMap, String[] headers, String fileName) throws IOException {// 预处理数据(校验和替换)List<String[]> preprocessedData = preprocessData(dataList, validationRulesMap);// 写入CSV文件writeCSV(preprocessedData, headers, fileName);}/*** 预处理数据(校验和替换)。** @param dataList       数据列表(泛型对象列表)* @param validationRulesMap 校验和替换规则映射(键为列索引,值为校验和替换规则的映射)* @return 预处理后的数据(字符串数组列表)*/private List<String[]> preprocessData(List<T> dataList, Map<Integer, Map<String, String>> validationRulesMap) {List<String[]> preprocessedData = new ArrayList<>(dataList.size());for (T data : dataList) {String[] rowData = convertObjectToArray(data);preprocessedData.add(validateAndReplace(rowData, validationRulesMap));}return preprocessedData;}/*** 从泛型对象中获取属性值并转换为字符串数组。** @param data 泛型对象* @return 字符串数组,包含对象的属性值*/private String[] convertObjectToArray(T data) {Class<?> clazz = data.getClass();Field[] fields = clazz.getDeclaredFields();// 获取对象的所有字段,并设置它们为可访问for (Field field : fields) {field.setAccessible(true);}String[] rowData = new String[fields.length];// 遍历所有字段,获取每个字段的值并添加到字符串数组中for (int i = 0; i < fields.length; i++) {try {rowData[i] = fields[i].get(data).toString();} catch (IllegalAccessException e) {throw new RuntimeException("Failed to access field value", e);}}return rowData;}/*** 根据提供的校验和替换规则对字符串数组进行校验和替换。** @param rowData   字符串数组* @param rulesMap 校验和替换规则映射(键为列索引,值为校验和替换规则的映射)* @return 校验和替换后的字符串数组*/private String[] validateAndReplace(String[] rowData, Map<Integer, Map<String, String>> rulesMap) {for (Map.Entry<Integer, Map<String, String>> entry : rulesMap.entrySet()) {int columnIndex = entry.getKey();Map<String, String> ruleMap = entry.getValue();String currentValue = rowData[columnIndex];if (ruleMap.containsKey(currentValue)) {rowData[columnIndex] = ruleMap.get(currentValue);}}return rowData;}/*** 将预处理后的数据写入CSV文件。** @param preprocessedData 预处理后的数据(字符串数组列表)* @param headers          CSV表头数组* @param fileName         导出CSV文件的名称* @throws IOException 如果在写入文件时发生错误*/private void writeCSV(List<String[]> preprocessedData, String[] headers, String fileName) throws IOException {try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {CSVWriter csvWriter = new CSVWriter(writer);// 写入表头csvWriter.writeNext(headers);// 写入数据csvWriter.writeAll(preprocessedData);csvWriter.close();}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/237659.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java String, StringBuffer StringBuilder 的区别

Java中的String, StringBuffer, 和 StringBuilder 都是用于处理字符串的类&#xff0c;但它们之间存在一些关键的差异&#xff0c;String 的长度是不可变的&#xff1b;StringBuffer 的长度是可变的&#xff0c;如果你对字符串中的内容经常进行操作&#xff0c;特别是内容要修改…

IgH调试注意事项

1&#xff0c;不要在虚拟机测试&#xff0c;否则IgH无法收发数据包 现象&#xff1a;虚拟机中运行IgH master并绑定网卡后&#xff0c;主站由ORPHANED状态转换成IDLE状态&#xff0c;但无法收发数据报。 这是因为虚拟机用的是虚拟网卡&#xff0c;需通过iptables将数据包到转…

八股文打卡day6——计算机网络(6)

面试题&#xff1a;GET请求和POST请求的区别 我的回答&#xff1a; 1.作用不同&#xff1a;GET是用来获取服务器资源的;POST是用来向服务器提交资源的&#xff1b; 2.参数传递方式不同&#xff1a;GET请求参数一般写在URL中的&#xff0c;只能接收ASCII字符&#xff1b;POST的…

【前端基础】script引入资源脚本加载失败解决方案(重新加载获取备用资源)

问题描述 现在假设有一个script资源加载失败&#xff0c;代码如下 <!DOCTYPE html> <html> <head><title>script 资源加载失败</title> </head> <body><script src"http:hdh.sdas.asdas/1.js"></script> &l…

openGuass:极简版安装

目录 一、openGauss简介 二、初始化安装环境 1.创建安装用户 2.修改文件句柄设置 ​3.修改SEM内核参数 4.关闭防火墙 6.禁用SELINUX 7.安装依赖软件 8.重启服务器 三、安装数据库 1.下载安装包 2.创建安装目录 3.解压安装包 4.执行安装 5.验证安装 四、gsql工具…

【大数据存储与处理】第一次作业

hbase 启动步骤 1、启动 hadoop&#xff0c;master 虚拟机&#xff0c;切换 root 用户&#xff0c;输入终端命令&#xff1a;start-all.sh 2、启动 zookeeper&#xff0c;分别在 master、slave1、slave2 虚拟机终端命令执行&#xff1a;zkServer.sh start 3、启动 hbase&#x…

Tomcat报404问题解决方案大全(包括tomcat可以正常运行但是报404)

文章目录 Tomcat报404问题解决方案大全(包括tomcat可以正常运行但是报404)1、正确的运行页面2、报错404问题分类解决2.1、Tomcat未配置环境变量2.2、IIs访问权限问题2.3、端口占用问题2.4、文件缺少问题解决办法&#xff1a; Tomcat报404问题解决方案大全(包括tomcat可以正常运…

04-JVM字节码文件结构深度剖析

一、源代码 package com.tuling.jvm;public class TulingByteCode {private String userName;public String getUserName() {return userName;}public void setUserName(String userName) {this.userName userName;} }二、通过javap -verbose TulingByteCode .class反编译 //…

yolov8-实例分割步骤

这里只说简单的训练步骤 v8实例分割的数据集和v5是通用的也是labelme标记的json文件转txt 下载yolov8代码 https://github.com/ultralytics/ultralytics安装训练环境创建一个python文件里面加入训练启动的代码 &#xff0c;然后通过pycharm启动如果没有数据集文件会自动下载&a…

【Spring Security】打造安全无忧的Web应用--进阶篇

&#x1f973;&#x1f973;Welcome Huihuis Code World ! !&#x1f973;&#x1f973; 接下来看看由辉辉所写的关于Spring Security的相关操作吧 目录 &#x1f973;&#x1f973;Welcome Huihuis Code World ! !&#x1f973;&#x1f973; 一.导入相关配置 1.pom 2.ym…

【sgDragUploadFolder】自定义组件:自定义拖拽文件夹上传组件,支持上传单个或多个文件/文件夹,右下角上传托盘出现(后续更新...)

特性&#xff1a; 支持在拖拽上传单个文件、多个文件、单个文件夹、多个文件夹可自定义headers可自定义过滤上传格式可自定义上传API接口支持显示/隐藏右下角上传队列托盘 sgDragUploadFolder源码 <template><div :class"$options.name" :dragenter"i…

.Net Core webapi RestFul 统一接口数据返回格式

在RestFul风格盛行的年代&#xff0c;大部分接口都需要一套统一的数据返回格式&#xff0c;那么我们怎么才能保证使用统一的json数据格式返回呢&#xff0c;下面给大家简单介绍一下&#xff1a; 假如我们需要接口统一返回一下数据格式&#xff1a; {"statusCode": …

【AI】ChatGLM3-6B模型API调用测试

之前将ChatGLM6B模型下载到本地运行起来了&#xff1a;ChatGLM3-6B上手体验&#xff1b;如果想要用在项目中&#xff0c;那么可以使用API调用的方式进行操作&#xff0c;尤其当你的项目还是不同语言的异构的场景下&#xff0c;其他服务需要调用的时候就可以直接通过请求服务来获…

vue和react diff的详解和不同

diff算法 简述&#xff1a;第一次对比真实dom和虚拟树之间的同层差别&#xff0c;后面为对比新旧虚拟dom树之间的同层差别。 虚拟dom 简述&#xff1a;js对象形容模拟真实dom 具体&#xff1a; 1.虚拟dom是存在内存中的js对象&#xff0c;利用内存的高效率运算。虚拟dom属…

LeetCode 20 有效的括号

题目描述 有效的括号 给定一个只包括 (&#xff0c;)&#xff0c;{&#xff0c;}&#xff0c;[&#xff0c;] 的字符串 s &#xff0c;判断字符串是否有效。 有效字符串需满足&#xff1a; 左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。每个右括号都有一…

微积分-三角函数4

2.4三角恒等式 让我们来回顾一下三角函数 sin ⁡ ( θ ) y r , cos ⁡ ( θ ) x r , tan ⁡ ( θ ) y x sec ⁡ ( θ ) 1 cos ⁡ ( θ ) &#xff0c; csc ⁡ ( θ ) 1 sin ⁡ ( θ ) , cot ⁡ 1 tan ⁡ ( θ ) \sin(\theta)\frac{y}{r},\cos(\theta)\frac{x}{r},\tan(…

二叉搜索树、AVL、红黑树

文章目录 二叉搜索树2. avl树3. 红黑树 二叉搜索树 找一个节点的前驱和后继&#xff1a; 前驱&#xff1a;如果节点有左子树&#xff0c;找左子树的最大值&#xff0c;如果没有左子树&#xff0c;找最近一个自右而来的节点 后继&#xff1a;如果节点有右子树&#xff0c;找右…

智能图像编辑软件Luminar Neo mac提供多种调整和滤镜选项

Luminar Neo mac是一款由Skylum公司开发的AI技术图像编辑软件&#xff0c;旨在为摄影师和视觉艺术家提供创意图像编辑解决方案。Luminar Neo拥有强大的AI技术和丰富的后期处理工具&#xff0c;可帮助用户快速轻松地实现从基本到高级的图像编辑需求。 Luminar Neo提供了多种调整…

同步与互斥(二)

一、谁上锁就由谁解锁&#xff1f; 互斥量、互斥锁&#xff0c;本来的概念确实是&#xff1a;谁上锁就得由谁解锁。 但是FreeRTOS并没有实现这点&#xff0c;只是要求程序员按照这样的惯例写代码。 main函数创建了2个任务&#xff1a; 任务1&#xff1…

先进制造身份治理现状洞察:从手动运维迈向自动化身份治理时代

在新一轮科技革命和产业变革的推动下&#xff0c;制造业正面临绿色化、智能化、服务化和定制化发展趋势。为顺应新技术革命及工业发展模式变化趋势&#xff0c;传统工业化理论需要进行修正和创新。其中&#xff0c;对工业化水平的判断标准从以三次产业比重标准为主回归到工业技…