poi导出多个sheet
时间: 2023-07-28 22:09:49 浏览: 94
要将多个sheet导出到一个Excel文件中,可以按照以下步骤进行操作:
1. 创建一个Workbook对象
```java
Workbook workbook = new XSSFWorkbook(); // 或者 new HSSFWorkbook()
```
2. 创建多个Sheet对象,并为每个Sheet设置名称
```java
Sheet sheet1 = workbook.createSheet("Sheet1");
Sheet sheet2 = workbook.createSheet("Sheet2");
```
3. 在每个Sheet中创建行和单元格,并设置数据
```java
// 在Sheet1中创建一行
Row row1 = sheet1.createRow(0);
// 在第一行中创建一个单元格,并设置数据
Cell cell1 = row1.createCell(0);
cell1.setCellValue("Sheet1 - Row 1 - Column 1");
// 在Sheet2中创建一行
Row row2 = sheet2.createRow(0);
// 在第一行中创建一个单元格,并设置数据
Cell cell2 = row2.createCell(0);
cell2.setCellValue("Sheet2 - Row 1 - Column 1");
```
4. 将Workbook对象写入到文件中
```java
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
workbook.write(fileOut);
fileOut.close();
```
完整代码示例:
```java
Workbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("Sheet1");
Sheet sheet2 = workbook.createSheet("Sheet2");
Row row1 = sheet1.createRow(0);
Cell cell1 = row1.createCell(0);
cell1.setCellValue("Sheet1 - Row 1 - Column 1");
Row row2 = sheet2.createRow(0);
Cell cell2 = row2.createCell(0);
cell2.setCellValue("Sheet2 - Row 1 - Column 1");
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
workbook.write(fileOut);
fileOut.close();
```
阅读全文