快来看看chatGpt写的导出百万数据到excel的代码

使用 Apache POI 库来实现大批量数据导出 Excel 的解决方案。

以下是示例代码:

// 创建工作簿
Workbook workbook = new XSSFWorkbook();

// 创建工作表
Sheet sheet = workbook.createSheet();

// 创建行
Row row = sheet.createRow(0);

// 创建单元格并设置值
Cell cell = row.createCell(0);
cell.setCellValue("姓名");

cell = row.createCell(1);
cell.setCellValue("年龄");

// 循环创建数据行
for (int i = 1; i <= 10000; i++) {
    row = sheet.createRow(i);
    cell = row.createCell(0);
    cell.setCellValue("张三" + i);

    cell = row.createCell(1);
    cell.setCellValue(i);
}

// 输出 Excel 文件
FileOutputStream outputStream = new FileOutputStream("data.xlsx");
workbook.write(outputStream);
outputStream.close();

上述代码创建了一个包含 10000 行数据的 Excel 文件。其中 Workbook 是工作簿,Sheet 是工作表,Row 是行,Cell 是单元格。具体操作就是先创建一个工作簿,再创建工作表,然后创建表头行,接着循环创建数据行,最后输出保存 Excel 文件。

重写,需要完整Java代码,要导出百万级的数据量到excel中

要导出百万级的数据量到 Excel 中,需要使用流式写入的方式,以避免一次性写入过多数据导致内存溢出。

以下是使用 Apache POI 库实现流式写入的示例代码:

public void exportDataToExcel(String filepath) throws IOException {
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Sheet1");

    // 写入表头
    Row headerRow = sheet.createRow(0);
    for (int i = 0; i < TABLE_HEADER.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(TABLE_HEADER[i]);
    }

    // 创建单元格格式,防止科学计数法显示
    CellStyle cellStyle = workbook.createCellStyle();
    DataFormat format = workbook.createDataFormat();
    cellStyle.setDataFormat(format.getFormat("0"));

    // 写入数据
    Connection conn = getConnection();
    Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    stmt.setFetchSize(FETCH_SIZE); // 设置每次从数据库取得的行数
    ResultSet rs = stmt.executeQuery("SELECT * FROM big_table");
    int rowIndex = 1;
    while (rs.next()) {
        Row dataRow = sheet.createRow(rowIndex++);
        for (int i = 0; i < TABLE_HEADER.length; i++) {
            Cell cell = dataRow.createCell(i);
            if (rs.getObject(i + 1) != null) {
                cell.setCellValue(rs.getDouble(i + 1));
                cell.setCellStyle(cellStyle); // 设置单元格格式
            }
        }
    }
    rs.close();
    stmt.close();
    conn.close();

    // 写出Excel文件
    FileOutputStream outputStream = new FileOutputStream(filepath);
    workbook.write(outputStream);
    outputStream.close();

    workbook.close();
}

上述代码中,FETCH_SIZE 是每次从数据库取得的行数,可以根据实际情况调整。getConnection() 是获取数据库连接的方法,此处省略了实现。TABLE_HEADER 是表头数组,表示 Excel 中的列名,此处省略了定义。

此代码示例中使用了流式写入的方式,可以在一定程度上优化内存占用,适用于大批量数据导出到 Excel 的场景。

Guess you like

Origin blog.csdn.net/a913222/article/details/130116669