https://github.com/alibaba/easyexcel/
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
实体类
@Lombok
public class DemoData {
//设置表头名称
@ExcelProperty(value = "学生编号", index = 0)
private int sno;
//设置表头名称
@ExcelProperty(value = "学生姓名", index = 1)
private String sname;
映射器
public class ExcelListener extends AnalysisEventListener<DemoData> {
//创建list集合封装最终的数据
List<DemoData> list = new ArrayList<DemoData>();
//一行一行去读取excle内容
@Override
public void invoke(DemoData user, AnalysisContext analysisContext) {
System.out.println("***" + user);
list.add(user);
}
//读取excel表头信息
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
System.out.println("表头信息:" + headMap);
}
//读取完成后执行
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
Demo
public class Test {
public static void main(String[] args) {
writeExcel1();
try {
readExcel();
} catch (Exception e) {
e.printStackTrace();
}
}
//循环设置要添加的数据,最终封装到list集合中
private static List<DemoData> data() {
List<DemoData> list = new ArrayList<DemoData>();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setSno(i);
data.setSname("张三" + i);
list.add(data);
}
return list;
}
//方式一
private static void writeExcel1() {
// 写法1
String fileName = "D:\\桌面\\Students.xls";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
// 如果这里想使用03 则 传入excelType参数即可
EasyExcel.write(fileName, DemoData.class).sheet("写入方法一").doWrite(data());
}
//方式二
private static void writeExcel2() {
// 写法2,方法二需要手动关闭流
String fileName = "D:\\桌面\\Students.xls";
// 这里 需要指定写用哪个class去写
ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet("写入方法二").build();
excelWriter.write(data(), writeSheet);
/// 千万别忘记finish 会帮忙关闭流
excelWriter.finish();
}
//Read
private static void readExcel() throws Exception {
//方式一
String fileName = "D:\\桌面\\Students.xls";
EasyExcel.read(fileName, DemoData.class, new ExcelListener()).sheet().doRead();
//方式二
InputStream in = new BufferedInputStream(new FileInputStream(fileName));
ExcelReader excelReader = EasyExcel.read(in, DemoData.class, new ExcelListener()).build();
ReadSheet readSheet = EasyExcel.readSheet(0).build();
excelReader.read(readSheet);
// 这里千万别忘记关闭,读的时候会创建临时文件,到时磁盘会崩的
excelReader.finish();
}
}
标签:Demo,EasyExcel,list,DemoData,fileName,class,void
From: https://www.cnblogs.com/leejk/p/17067124.html