草庐IT

Java导出大批量数据(分批查询导出篇)

夜の雨 2023-04-21 原文

上篇文章介绍了java导出文件格式篇xls,xlsx,csvhttps://blog.csdn.net/weixin_56567361/article/details/126640185

本篇介绍下 大批量数据的导出思路和方法

导出数据慢的原因:

一次性查询太多数据 sql会很慢 太多数据导出处理很慢

这里我讲解下分批查询和分批导出

目录

分批查询方法

一: 根据数据量 分割每一部分数据

二: 根据查询时间间隔 分割为每一天一个时间段

分批查询+分批导出实例


分批查询方法

一: 根据数据量 分割每一部分数据

//查询总条数
int count = testService.selectSize(test);
//数据量分割值10万
int num = 100000;
//循环次数/分割次数
int cycles = count / num;
//余数
int remainder = count % num;
String sql = "";
List<List<Test>> getDownloadList = new ArrayList<>();
//分批查询次数
for (int i = 0; i < cycles; i++) {
//sql=select .... from test where .... order by create_time " + " limit " + (i * num) + "," + num;
//limit前参数
test.setFront(i * num);
//limit后参数
test.setAfter(num);
List<Test>testList = testService.selectAll(test);
getDownloadList.addAll(testList);
}
if (remainder > 0) {
test.setFront(num * cycles);
test.setAfter((num * cycles) + remainder);
//sql=select .... from test where .... order by create_time " + " limit " + (num * cycles) + "," + ((num * cycles) + remainder);
List<Test>testList = testService.selectAll(test);
getDownloadList.addAll(testList);
}
//导出操作
.....

二: 根据查询时间间隔 分割为每一天一个时间段

Long beginTime = ...;(毫米级)
Long endTime = ...;
List<List<Test>> getDownloadList = new ArrayList<>();
//对查询时间进行分割 每天查一次 map中时间顺序 从小到大
Map<String, String> timeMap = new LinkedHashMap<>();
if (endTime - beginTime > 86400) {
    //要查询分割的次数
    int l = (int) ((endTime - beginTime) / 86400);
    for (int i = 1; i <= l; i++) {
        timeMap.put(DateUtils.longToString(beginTime + (i - 1) * 86400), DateUtils.longToString(beginTime + (i * 86400)));
    }
    //查询间隔不是整天数时 则补余下时间
    if (beginTime + l * 86400 != endTime) {
        timeMap.put(DateUtils.longToString(beginTime + (l * 86400)), DateUtils.longToString(endTime));
    }
} else {
    //小于一天时处理
    timeMap.put(DateUtils.longToString(beginTime), DateUtils.longToString(endTime));
}
//如果数据展示要倒序 需要将map中时间翻过来
List<String> times = new ArrayList<>(timeMap.keySet());
Collections.reverse(times);
for (String beginTimeStr : times) {
String endTimeStr = timeMap.get(beginTimeStr);
sql:.....
List<Test>testList=......;
getDownloadList.addAll(testList);
}
//导出操作
.....


/**
* long类型时间戳(秒级)转String 1654012800 --> 2022-06-01 00:00:00
*
* @param value
* @return
*/
public static String longToString(long value) {
if (String.valueOf(value).length() == 10) {
    value = value * 1000;
}
    Date time = new Date(value);
    return formatYMDHMS.format(time);
}

分批查询+分批导出实例

controller层


            if ((endTime - beginTime) / (3600 * 24) > 31) {
                throw new CustomException("一次最多请求31天数据,请分批导出");
            }
            String sql = "select count(1) as count" + " from test where create_time between " + beginTime + " and " + endTime";
            List<Map<String, Object>> mapList = ClickHouseUtils.execSQL(sql);
            //根据数据量分割上传 也可根据时间
            int count = Integer.parseInt(mapList.get(0).get("count").toString());
            //数据量分割值20万
            int num = 200000;
            //循环次数/分割次数
            int cycles = count / num;
            //余数
            int remainder = count % num;
            String path = getDefaultBaseDir();
            String csvFile = "临时历史数据.csv";
            String absolutePath = path + "/" + csvFile;
            //获取表头
            String[] exportDataTitle = dataService.exportDataTitle(fields);
            File file = new File(path);
            //检查是否存在此文件夹 如没有则创建
            if (!file.exists()) {
                if (file.mkdirs()) {
                    logger.info("历史查询目录创建成功");
                } else {
                    logger.error("历史查询目录创建失败");
                }
            }
            for (int i = 0; i < cycles; i++) {
                sql = "select .. from test where create_time between " + beginTime + " and " + endTime + " order by create_time limit " + (i * num) + "," + num;
                FileVO fileVO = dataService.fileVO(sql, ids, fields);
                PoiUtils.exportCSVFile(exportDataTitle, fileVO.getDownloadList(), i, absolutePath);
            }
            if (remainder > 0) {
                sql = "select .. from test where create_time between " + beginTime + " and " + endTime + " order by create_time limit " + (num * cycles) + "," + ((num * cycles) + remainder);
                FileVO fileVO = dataService.fileVO(sql, ids, fields);
                PoiUtils.exportCSVFile(exportDataTitle, fileVO.getDownloadList(), cycles, absolutePath);
            }
            //输出csv流文件,提供给浏览器下载
            PoiUtils.outCsvStreamCSV(response, absolutePath);
            logger.info("历史查询下载目录: " + absolutePath);
            //删除临时文件
            PoiUtils.deleteFile(new File(absolutePath));
            logger.info("历史查询删除目录: " + absolutePath);
PoiUtils层
    /**
     * 上传csv文件到服务器
     *
     * @param title
     * @param downloadList
     * @param i
     * @param absolutePath
     * @throws IOException
     */
    public static void exportCSVFile(String[] title, List<List<String>> downloadList, int i, String absolutePath) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(absolutePath, true));
        logger.info("创建文件地址: " + absolutePath);
        //如果是第一次循环 添加表头
        if (i == 0) {
            PoiUtils.writeHead(title, bufferedWriter);
            //另起一行
            bufferedWriter.newLine();
        }
        //循环list中数据 逐个添加
        for (List<String> list : downloadList) {
            CSVFileUtil.writeRow(list, bufferedWriter);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
    }


    /**
     * csv文件表头写入
     *
     * @param title
     * @param bufferedWriter
     * @throws IOException
     */
    public static void writeHead(String[] title, BufferedWriter bufferedWriter) throws IOException {
        // 写表头
        int i = 0;
        for (String data : title) {
            bufferedWriter.write(data);
            if (i != title.length - 1) {
                bufferedWriter.write(",");
            }
            i++;
        }
    }

/**
     * 分割csv文件传浏览器
     *
     * @param response
     * @param absolutePath
     * @throws IOException
     */
    public static void outCsvStreamCSV(HttpServletResponse response, String absolutePath) throws IOException {
        java.io.OutputStream out = response.getOutputStream();
        byte[] b = new byte[10240];
        java.io.File fileLoad = new java.io.File(absolutePath);
        response.reset();
        response.setContentType("application/csv");
        response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode("export.csv", "UTF-8"));
        java.io.FileInputStream in = new java.io.FileInputStream(fileLoad);
        int n;
        //为了保证excel打开csv不出现中文乱码
        out.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
        while ((n = in.read(b)) != -1) {
            //每次写入out1024字节
            out.write(b, 0, n);
        }
        in.close();
        out.close();
    }

CSVFileUtils

/**
 * csv导出工具类
 */
@Slf4j
public class CSVFileUtil {
    /**
     * 读取
     *
     * @param file      csv文件(路径+文件)
     * @param delimiter 分割符
     * @return
     */
    public static List<String[]> importCsv(File file, String delimiter, String charsetName) {
        List<String[]> dataList = new ArrayList<>();
        BufferedReader br = null;
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), charsetName);
            br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null) {
                dataList.add(line.split(delimiter));
            }
        } catch (Exception e) {
        } finally {
            if (br != null) {
                try {
                    br.close();
                    br = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return dataList;
    }

    /**
     * 写入
     * csv文件(路径+文件名),csv文件不存在会自动创建
     *
     * @param exportData 数据
     * @return
     */
    public static File exportCsv(List<List<String>> exportData, String outPutPath, String fileName) {
        File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            File file = new File(outPutPath);
            if (!file.exists()) {
                if (file.mkdirs()) {
                    log.info("创建成功");
                } else {
                    log.error("创建失败");
                }
            }
            //定义文件名格式并创建
            csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile, true), StandardCharsets.UTF_8), 1024);
            for (List<String> exportDatum : exportData) {
                writeRow(exportDatum, csvFileOutputStream);
                csvFileOutputStream.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (csvFileOutputStream != null) {
                    csvFileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    /**
     * 写一行数据
     *
     * @param row       数据列表
     * @param csvWriter
     * @throws IOException
     */
    public static void writeRow(List<String> row, BufferedWriter csvWriter) throws IOException {
        int i = 0;
        for (String data : row) {
            csvWriter.write(data);
            if (i != row.size() - 1) {
                csvWriter.write(",");
            }
            i++;
        }
    }

    /**
     * 剔除特殊字符
     *
     * @param str 数据
     */
    public static String DelQuota(String str) {
        String result = str;
        String[] strQuota = {"~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?"};
        for (String s : strQuota) {
            if (result.contains(s)) {
                result = result.replace(s, "");
            }
        }
        return result;
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        exportCsv();
        //importCsv();
    }

    /**
     * CSV读取测试
     *
     * @throws Exception
     */
    public static void importCsv() {
        List<String[]> dataList = CSVFileUtil.importCsv(new File("F:/test_two.csv"), ",", "GB2312");
        if (!dataList.isEmpty()) {
            for (String[] cells : dataList) {
                if (cells != null && cells.length > 0) {
                    for (String cell : cells) {
                        System.out.print(cell + "  ");
                    }
                    System.out.println();
                }
            }
        }
    }

    /**
     * CSV写入测试
     *
     * @throws Exception
     */
    public static void exportCsv() {
        List<List<String>> listList = new ArrayList<>();

        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        List<String> list3 = new ArrayList<>();
        list1.add("编号");
        list1.add("姓名");
        list1.add("身高");
        list1.add("电话");

        list2.add("1");
        list2.add("小明");
        list2.add("180cm");
        list2.add("1111111");

        list3.add("2");
        list3.add("小红");
        list3.add("176cm");
        list3.add("1111111");

        listList.add(list1);
        listList.add(list2);
        listList.add(list3);

        CSVFileUtil.exportCsv(listList, "D://", "testFile");
    }
}

到这里分批查询+分批导出已经介绍完了

大家根据需求调整代码 根据源码多测试

最后有遇到什么问题可以留言告诉我哦 欢迎评论区讨论🤪

有关Java导出大批量数据(分批查询导出篇)的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  4. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  5. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  8. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  9. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  10. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

随机推荐