Java实现大数据量的excel文件下载

292 阅读1分钟

背景

在管理系统中,当用户需要下载大量的数据文件的时候,依赖前端的批次调用下载就会很慢,甚至可能卡死页面,这个时候就需要在后端进行下载处理,由于CSV文件又叫做逗号分隔符文件,文件大小相对没有那么大,所以下载为csv文件进行处理

实现原理

处理方式,主要有两点: 1,数据分批次写入文件 2,多线程处理文件写入方式,每个线程操作完毕,将数据从暂存区写入文件 具体流程图如下:

image.png

核心代码

public static void writeCsv(String fileUrl, List<String> dataList, int perCount) throws IOException {
    File writeFile = new File(fileUrl);
    BufferedWriter writeText = new BufferedWriter(new FileWriter(writeFile,true));
    List<CompletableFuture> threads = new ArrayList<>();
    for (List<String> itemList : Lists.partition(dataList, perCount)) {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                synchronized (writeText){
                    for(int i=0;i<itemList.size();i++){
                        String str = itemList.get(i);
                        writeText.newLine();    //换行
                        writeText.append(str);
                    }
                    writeText.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        threads.add(future);
    }
    CompletableFuture<Void> resultFuture = CompletableFuture.allOf(threads.toArray(new CompletableFuture[threads.size()]));
    resultFuture.join();
    log.info("数据分批写入csv文件完成");
}