EasyExcel 简单介绍
- AnalysisEventListener EasyExcel 提供的抽象类 继承该类可以灵活操作 读取的 excel 数据
- AbstractRowWriteHandler EastExcel 提供的抽象类,继承此类可以灵活设置 excel 样式,使用原生 poi 接口,正常使用无需关注
- EasyExcelListener 是我抽象出来的 平时如果没有对导入的 excel 数据灵活操作的都可以使用该类,正常使用无需关注
注解介绍
@ExcelProperty
@ExcelIgnore
@ExcelIgnoreUnannotated
@DateTimeFormat
@NumberFormat
@ColumnWidth
@ContentFontStyle
@ContentLoopMerge
@ContentRowHeight
@ContentStyle
@HeadFontStyle
@HeadRowHeight /表格的头高度设置
@HeadStyle
@OnceAbsoluteMerge
简单使用
上传
@PostMapping("/upload")
@ResponseBody
public List<TestEasyData> upload(MultipartFile file) throws IOException {
List<TestEasyData> testEasyData = EasyExcelUtil.readExcel(file.getInputStream(), TestEasyData.class);
return testEasyData;
}
下载
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
List<TestEasyData> data = data();
EasyExcelUtil.writeExcel(response,"测试工具类",data,TestEasyData.class,"第一个表格");
}
工具类封装
public class EasyExcelUtil {
public static <T> List<T> readExcel(InputStream stream, Class<T> tClass) {
return readExcel(stream,tClass,1);
}
public static <T> List<T> readExcel(InputStream stream, Class<T> tClass,Integer sheetNo) {
if (Objects.isNull(sheetNo)||sheetNo==0){
sheetNo=1;
}
EasyExcelListener<T> listener=new EasyExcelListener<T>();
EasyExcel.read(stream, tClass, listener).sheet(sheetNo-1).doRead();
return listener.getDatas();
}
public static <T> void writeExcel(OutputStream outputStream,List<T> list,Class clazz,String sheetName) {
EasyExcel.write(outputStream,clazz).sheet(sheetName).doWrite(list);
}
public static <T> void writeExcel(HttpServletResponse response, String fileName, List<T> list, Class<T> clazz, String sheetName) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileNameEnCode = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "+");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameEnCode + ".xlsx");
writeExcel(response.getOutputStream(),list,clazz,sheetName);
}
}
使用到的类
java
@Data
// 头背景设置
@HeadStyle(fillPatternType = FillPatternType.NO_FILL, fillForegroundColor = 10)
// 头字体设置成20
@HeadFontStyle(fontHeightInPoints = 12)
@HeadRowHeight(value = 60)
public class TestEasyData {
@ExcelProperty(value = "编码")
private String code;
@ExcelProperty(value = "名字")
private String name;
@ExcelProperty(value = "数字")
private Double number;
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于