POM依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.0</version>
</dependency>
创建实体类
根据你想要的Excel文件表头创建对应的实体类:
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class WaiteExcel {
// value 是excel文件的表头 index 是第几列
@ExcelProperty(value = "用户名", index = 0)
private String name;
@ExcelProperty(value = "年龄", index = 1)
private String age;
@ExcelProperty(value = "性别", index = 2)
private String gender;
}
写入Excel文件
public static void main(String[] args) {
// 写入文件的路径
final String excelFilePath = "D:/waiteExcel.xlsx";
try {
// 判断文件是否存在, 不存在则创建
File file = new File(excelFilePath);
if (!file.exists()) {
file.createNewFile();
}
// 向Excel中写入数据
EasyExcel.write(excelFilePath, WaiteExcel.class)
.sheet("写入的Sheet") // Sheet 自定义名称
.doWrite(handleWaiteExcelList()); // 写入的数据(此处写入的是一个列表)
} catch (IOException e) {
log.error("{}", e);
} catch (Exception e) {
log.error("{}", e);
}
}
在我的电脑D盘中就成功创建了waiteExcel文件
waiteExcel文件中的数据也被写入进来了