1.读取excel
读监听器
@Slf4j
public class StudentReadListener extends AnalysisEventListener<Student> {
// 每读一样,会调用该invoke方法一次
@Override
public void invoke(Student data, AnalysisContext context) {
System.out.println("data = " + data);
log.info(data + "保存成功");
}
// 全部读完之后,会调用该方法
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// TODO......
}
}
映射实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ColumnWidth(20)
@ToString
public class Student {
/**
* id
*/
@ExcelProperty(value = "编号",index = 0)
//@ExcelIgnore
private String id;
/**
* 学生姓名
*/
@ExcelProperty(value = "学生姓名", index = 1)
//@ColumnWidth(30)
private String name;
/**
* 学生性别
*/
@ExcelProperty(value = "学生性别", index = 2)
private String gender;
/**
* 学生出生日期
*/
@ExcelProperty(value = "学生出生日期", index = 3)
//@ColumnWidth(20)
private Date birthday;
读取
public class StudentReadDemo {
public static void main(String[] args) throws FileNotFoundException {
// 读取文件,读取完之后会自动关闭
/*
pathName 文件路径;"C:\\Users\\wjg\\Desktop\\学员信息.xlsx"
head 每行数据对应的实体;Student.class
readListener 读监听器,每读一样就会调用一次该监听器的invoke方法
sheet方法参数: 工作表的顺序号(从0开始)或者工作表的名字,不传默认为0
*/
// 封装工作簿对象
ExcelReaderBuilder workBook = EasyExcel.read
("C:\\Users\\wjg\\Desktop\\学员信息.xlsx", Student.class, new StudentReadListener());
// 封装工作表
ExcelReaderSheetBuilder sheet1 = workBook.sheet();
// 读取
sheet1.doRead();
}
2.写入excel
public class StudentWriteDemo {
public static void main(String[] args) {
List<Student> students = initData();
/*
String pathName 写入文件的路径
Class head 写入文件的对象类型
默认写入到07的xlsx中,如果想要写入xls,可以指定类型(待验证)
*/
ExcelWriterBuilder workBook = EasyExcel.write("C:\\Users\\wjg\\Desktop\\学员信息.xlsx", Student.class);
// sheet方法参数: 工作表的顺序号(从0开始)或者工作表的名字
workBook.sheet().doWrite(students);
}
private static List<Student> initData() {
ArrayList<Student> students = new ArrayList<Student>();
Student data = new Student();
for (int i = 0; i < 10; i++) {
data.setName("学号0" + i);
data.setBirthday(new Date());
data.setGender("男");
data.setId(String.valueOf(i));
students.add(data);
}
return students;
}
}