用java代码将1w条数据导入到excel的五张表
时间: 2023-05-23 09:04:22 浏览: 273
java数据导入到Excel表
A:
可以使用Apache POI来编写Java代码将1w条数据导入Excel的五张表中。具体步骤如下:
1. 创建Excel文件和工作表
```
Workbook workbook = new XSSFWorkbook(); // 创建一个Excel文件(.xlsx)
for (int i = 0; i < 5; i++) {
Sheet sheet = workbook.createSheet("Sheet" + (i + 1)); // 创建五个工作表
// 添加表头(第一行)
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("ID");
row.createCell(1).setCellValue("Name");
row.createCell(2).setCellValue("Age");
...
}
```
2. 将数据导入Excel表格
```
// 假设数据存放在List集合中
List<Data> dataList = new ArrayList<>();
...
for (int i = 0; i < dataList.size(); i++) {
Data data = dataList.get(i);
Sheet sheet = workbook.getSheet("Sheet" + (i % 5 + 1)); // 选择第(i%5+1)个工作表
Row row = sheet.createRow(i + 1); // 创建行
row.createCell(0).setCellValue(data.getId());
row.createCell(1).setCellValue(data.getName());
row.createCell(2).setCellValue(data.getAge());
...
}
```
3. 保存Excel文件
```
String filePath = "path/to/save/excel";
FileOutputStream fos = new FileOutputStream(filePath);
workbook.write(fos);
fos.close();
```
完整代码:
```
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
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.usermodel.XSSFWorkbook;
public class ExcelExporter {
public static void main(String[] args) throws Exception {
// 创建一个Excel文件
Workbook workbook = new XSSFWorkbook();
for (int i = 0; i < 5; i++) {
Sheet sheet = workbook.createSheet("Sheet" + (i + 1)); // 创建五个工作表
// 添加表头(第一行)
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("ID");
row.createCell(1).setCellValue("Name");
row.createCell(2).setCellValue("Age");
// ...
}
// 将数据导入Excel表格
List<Data> dataList = new ArrayList<>(); // 假设数据存放在List集合中
for (int i = 0; i < dataList.size(); i++) {
Data data = dataList.get(i);
Sheet sheet = workbook.getSheet("Sheet" + (i % 5 + 1)); // 选择第(i%5+1)个工作表
Row row = sheet.createRow(i + 1); // 创建行
row.createCell(0).setCellValue(data.getId());
row.createCell(1).setCellValue(data.getName());
row.createCell(2).setCellValue(data.getAge());
// ...
}
// 保存Excel文件
String filePath = "path/to/save/excel";
FileOutputStream fos = new FileOutputStream(filePath);
workbook.write(fos);
fos.close();
}
// 定义数据类
static class Data {
private int id;
private String name;
private int age;
public Data(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
```
阅读全文