java写入数据到excel
时间: 2023-10-04 15:10:46 浏览: 46
要写入数据到Excel文件,可以使用Apache POI库。以下是一个简单的Java代码示例,演示如何使用POI将数据写入Excel文件:
```java
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelWriter {
public static void main(String[] args) throws Exception {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建数据行并添加数据
Row row = sheet.createRow(0);
Cell cell1 = row.createCell(0);
cell1.setCellValue("姓名");
Cell cell2 = row.createCell(1);
cell2.setCellValue("年龄");
Row row2 = sheet.createRow(1);
Cell cell3 = row2.createCell(0);
cell3.setCellValue("张三");
Cell cell4 = row2.createCell(1);
cell4.setCellValue(20);
Row row3 = sheet.createRow(2);
Cell cell5 = row3.createCell(0);
cell5.setCellValue("李四");
Cell cell6 = row3.createCell(1);
cell6.setCellValue(25);
// 保存Excel文件
FileOutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("Excel文件已成功写入。");
}
}
```
这个示例创建了一个XSSFWorkbook工作簿,然后创建了一个名为"Sheet1"的工作表。接下来,它添加了一些数据行和单元格,然后将工作簿写入名为"example.xlsx"的文件。最后,它关闭了工作簿和文件流。
请注意,这里使用的是XSSFWorkbook类,它可以写入.xlsx格式的Excel文件。如果您要写入.xls格式的Excel文件,则需要使用HSSFWorkbook类。