EasyExcel如何追加数据
时间: 2023-11-22 11:42:23 浏览: 267
使用EasyExcel进行数据追加的步骤如下:
1. 创建EasyExcel对象,加载要追加数据的Excel文件。
```java
EasyExcel excel = EasyExcelFactory.read(new FileInputStream("test.xlsx")).build();
```
2. 获取要追加数据的Sheet对象。
```java
ExcelReaderSheetBuilder sheetBuilder = new ExcelReaderSheetBuilder().sheetNo(0);
Sheet sheet = excel.getReader(sheetBuilder).getSheet();
```
3. 获取Sheet对象的最后一行的行号。
```java
int lastRowNum = sheet.getLastRowNum();
```
4. 创建要追加的数据对象的List集合。
```java
List<Object> data = new ArrayList<>();
data.add("张三");
data.add(20);
data.add(true);
```
5. 创建一个新的Row对象,设置要追加的数据。
```java
Row row = sheet.createRow(lastRowNum + 1);
for (int i = 0; i < data.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellValue(data.get(i).toString());
}
```
6. 保存Excel文件。
```java
excel.write(new FileOutputStream("test.xlsx"));
```
完整代码示例:
```java
EasyExcel excel = EasyExcelFactory.read(new FileInputStream("test.xlsx")).build();
ExcelReaderSheetBuilder sheetBuilder = new ExcelReaderSheetBuilder().sheetNo(0);
Sheet sheet = excel.getReader(sheetBuilder).getSheet();
int lastRowNum = sheet.getLastRowNum();
List<Object> data = new ArrayList<>();
data.add("张三");
data.add(20);
data.add(true);
Row row = sheet.createRow(lastRowNum + 1);
for (int i = 0; i < data.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellValue(data.get(i).toString());
}
excel.write(new FileOutputStream("test.xlsx"));
```
阅读全文