java如何使用游标分批次导出数据到excel, 给出示例代码
时间: 2024-03-25 14:36:55 浏览: 110
Java可以使用Apache POI库来操作Excel文件,以下是使用游标分批次导出数据到Excel的示例代码:
```java
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
public class ExportDataToExcel {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "123456";
String sql = "SELECT * FROM mytable";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
// 设置每次读取数据的大小,可以根据实际情况调整
int fetchSize = 1000;
stmt.setFetchSize(fetchSize);
// 创建Workbook和Sheet对象
SXSSFWorkbook wb = new SXSSFWorkbook();
wb.setCompressTempFiles(true);
String sheetName = "Sheet1";
int rownum = 0;
int sheetIndex = 0;
int columnCount = rs.getMetaData().getColumnCount();
String[] headers = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
headers[i - 1] = rs.getMetaData().getColumnLabel(i);
}
Row headerRow = wb.createSheet(sheetName + sheetIndex).createRow(rownum++);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
// 读取数据,并写入Workbook
while (rs.next()) {
if (rownum % fetchSize == 0) {
// 每次读取fetchSize行数据,写入一个新的Sheet
sheetIndex++;
headerRow = wb.createSheet(sheetName + sheetIndex).createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
rownum = 1;
}
Row row = wb.getSheet(sheetName + sheetIndex).createRow(rownum++);
for (int i = 1; i <= columnCount; i++) {
Cell cell = row.createCell(i - 1);
cell.setCellValue(rs.getString(i));
}
}
// 将Workbook写入文件
String fileName = "data.xlsx";
FileOutputStream out = new FileOutputStream(fileName);
wb.write(out);
out.close();
wb.dispose();
System.out.println("数据导出成功!");
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
需要注意的是,使用游标分批次读取数据可以减小内存消耗,但是可能会影响性能,因此需要根据实际情况选择适合的读取方式。另外,由于SXSSFWorkbook使用了临时文件来缓存数据,因此需要调用dispose方法来清除临时文件。
阅读全文