分批将数据导入Excel,模拟数据

1、pom.xml

1
2
3
4
5
6
7
8
9
10
<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.0.0</version>
    </dependency>

  

2、BatchExcelExport类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.feng.controller.excel;
 
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
public class BatchExcelExport {
 
    public static void main(String[] args) {
        // 生成测试数据,共10000行
        List<String[]> data = generateTestData(10000);
        String filePath = "D:\\feng\\export\\data_batch.xlsx";
        int batchSize = 1000; // 每批次写入1000行
 
        exportExcel(data, filePath, batchSize);
    }
 
    public static void exportExcel(List<String[]> data, String filePath, int batchSize) {
        int totalRows = data.size();
        int totalBatches = (int) Math.ceil((double) totalRows / batchSize);
 
        for (int batchNumber = 0; batchNumber < totalBatches; batchNumber++) {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");
 
            int startRow = batchNumber * batchSize;
            int endRow = Math.min(startRow + batchSize, totalRows);
 
            for (int i = startRow; i < endRow; i++) {
                Row row = sheet.createRow(i - startRow);
                String[] rowData = data.get(i);
                for (int j = 0; j < rowData.length; j++) {
                    row.createCell(j).setCellValue(rowData[j]);
                }
            }
 
            // 将工作簿写入文件输出流
            try (FileOutputStream fileOut = new FileOutputStream(filePath.replace(".xlsx", "_" + (batchNumber + 1) + ".xlsx"))) {
                workbook.write(fileOut);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
 
    public static List<String[]> generateTestData(int rows) {
        List<String[]> data = new ArrayList<>();
        for (int i = 0; i < rows; i++) {
            data.add(new String[]{"Name" + i, "Age" + i, "City" + i});
        }
        return data;
    }
}

  

posted @   Amy清风  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示