QQ截图20210423171019.jpg
controller
public static List<ExcleData> getExcleList() {
return Arrays.asList(
new ExcleData("学生1", 18, "学习", 59.5F),
new ExcleData("学生2", 19, "游泳", 68F),
new ExcleData("学生3", 19, "游泳", 90F),
new ExcleData("学生4", 19, "游泳", 100F)
);
}
@PostMapping("/write_excle")
public static void write_excle(String[] args) {
String fileName = "G:\\java-static\\imgs\\xx.xlsx";
EasyExcel.write(fileName, ExcleData.class).sheet("学生信息").doWrite(getExcleList());
}
@PostMapping("/read_excle")
public static void main(String[] args) {
String fileName = "G:\\java-static\\imgs\\xx.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
EasyExcel.read(fileName, ExcleData.class, new DemoDataListener()).sheet().doRead(); //仅打印
List<ExcleData> lists = EasyExcel.read(fileName, ExcleData.class, new DemoDataListener()).sheet().doReadSync(); //返回list用于存于数据库等
System.out.println("lists:" + lists.get(0) + lists.get(0).getName());
}
Data
package com.ruhua.java.dao;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor //如果加上面一个注解,这个必须加上,否则easy excel会报无法实例化
public class ExcleData {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("年龄")
private Integer age;
@ExcelProperty("爱好")
private String hobby;
@ExcelProperty("分数")
private Float score;
}
Listener
package com.ruhua.java.util;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruhua.java.dao.ExcleData;
public class DemoDataListener extends AnalysisEventListener<ExcleData> {
public DemoDataListener() {}
//解析每条数据的时候会调用这个方法
@Override
public void invoke(ExcleData student, AnalysisContext analysisContext) {
System.out.println(student);
}
//解析完成后调用这个方法
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
网友评论