java导出百万数据到excel
时间: 2023-09-14 20:11:52 浏览: 82
java导出大批量(百万以上)数据的excel文件
以下是Java导出百万数据到Excel的示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
public class ExcelExporter {
private static final int ROW_ACCESS_WINDOW_SIZE = 100;
private List<String[]> data;
public ExcelExporter() {
data = new ArrayList<>();
// 添加百万条数据到列表中
for (int i = 1; i <= 1000000; i++) {
String[] row = { "数据" + i, "数据" + i, "数据" + i };
data.add(row);
}
}
public void export(String fileName) throws IOException {
Workbook workbook = new SXSSFWorkbook(ROW_ACCESS_WINDOW_SIZE);
Sheet sheet = workbook.createSheet("Sheet1");
int rowIndex = 0;
for (String[] rowData : data) {
Row row = sheet.createRow(rowIndex++);
int cellIndex = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(cellIndex++);
cell.setCellValue(cellData);
}
}
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
outputStream.close();
workbook.close();
}
}
```
使用示例:
```java
public class Example {
public static void main(String[] args) {
ExcelExporter exporter = new ExcelExporter();
try {
exporter.export("data.xlsx");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该示例使用Apache POI库创建一个XLSX格式的Excel文件,使用SXSSFWorkbook类可以将数据写入到Excel中,并且使用分页窗口技术来提高性能,避免内存溢出。
阅读全文