使用easyexcel处理excel
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* JavaBean与Excel之间的关系映射
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ERReport extends BaseRowModel {
@ExcelProperty(value = "省", index = 0)
private String province;
@ExcelProperty(value = "市", index = 1)
private String city;
@ExcelProperty(value = "学校", index = 2)
private String school;
@ExcelProperty(value = "班级", index = 3)
private String classs;
@ExcelProperty(value = "老师", index = 4
private String teacher;
}
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.google.common.collect.Lists;
/**
* 自定义Listener继承AnalysisEventListener,重写invoke方法,为了方便获取值,添加了一个getData的方法
*/
public class ExcelListener<T extends BaseRowModel> extends AnalysisEventListener<T> {
private final List<T> data = Lists.newArrayList();
@Override
public void invoke(T t, AnalysisContext analysisContext) {
data.add(t);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
public List<T> getData(){
return data;
}
public class ExcelUtils {
/**
* 读取excel的方法
*/
public static <T extends BaseRowModel> List<T> readExcel(final InputStream inputStream, final Class<? extends BaseRowModel> clazz) {
if (null == inputStream) {
throw new NullPointerException("the inputStream is null!");
}
AnalysisEventListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, null, listener);
reader.read(new com.alibaba.excel.metadata.Sheet(1, 1, clazz));
return ((ExcelListener) listener).getData();
}
public static void main(String[] args) throws Exception {
String filePath = "C:\\Users\\Administrator\\Desktop\\test.xlsx";
List<ERReport> datas = ExcelUtils.readExcel(new FileInputStream(new File(filePath)), ERReport.class);
datas.forEach(System.out::println);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.