java中excel导出
时间: 2024-06-14 12:06:46 浏览: 60
以下是两种Java中导出Excel的方式:
1. 使用Apache POI库进行Excel导出
```java
// 创建工作簿
Workbook workbook = new HSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建行
Row row = sheet.createRow(0);
// 创建单元格
Cell cell = row.createCell(0);
// 设置单元格的值
cell.setCellValue("Hello World!");
// 导出Excel文件
try (OutputStream outputStream = new FileOutputStream("output.xls")) {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
```
2. 使用EasyExcel库进行Excel导出
```java
// 创建导出数据列表
List<User> userList = new ArrayList<>();
userList.add(new User("John", 25));
userList.add(new User("Alice", 30));
// 导出Excel文件
String fileName = "output.xlsx";
String sheetName = "Sheet1";
ExcelWriter excelWriter = EasyExcel.write(fileName).build();
WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
excelWriter.write(userList, writeSheet);
excelWriter.finish();
```
阅读全文