一 POM文件 版本更新快,可以自行搜jar依赖
二 非必要依赖
Lombok:在生成模板类型可以使用,简便快捷,不用大量去写setter与getter和构造方法
常见Excel导入导出问题都存在类型转换类型,所以必备的三种常见类型转换
日期类
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /* * @author: GODV * @date: 2020/2/5 23:38 * @params * @return: * @@Description: 日期辅助处理 */ public class DateUtil { /* * @author: GODV * @date: 2020/2/5 23:38 * @params * @return: * @@Description: 根据出生日期来计算年龄 */ public static int getAge(Date date) { if (date == null) { return 0; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); //2000 int year = calendar.get(Calendar.YEAR); Calendar now = Calendar.getInstance(); //2019 int nowYear = now.get(Calendar.YEAR); return nowYear - year == 0 ? 1 : nowYear - year; } /* * @author: GODV * @date: 2020/2/5 23:39 * @params * @return: * @@Description: String--->Date */ public static Date getBirthday(String date) { if (date == null) { return null; } if (("").equals(date)){ return null; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date birthday = null; try { birthday = format.parse(date); } catch (Exception e) { e.printStackTrace(); birthday = null; } return birthday; } /* * @author: GODV * @date: 2020/2/5 23:39 * @params * @return: * @@Description: Date--->String */ public static String fomartBirthday(Date date) { if (date == null) { return ""; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String birthday = format.format(date); return birthday; } /* * @author: GODV * @date: 2020/2/5 23:52 * @params * @return: * @@Description: 获取时间 */ public static Date getLocalDate(){ Date now =new Date(); return now; } /* * @author: GODV * @date: 2020/2/16 18:50 * @params 分钟化秒 * @return: * @@Description: TODO(10分钟有效验证码) */ public static String activeDate(Date date ,int time){ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); int s = time*60; Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); Calendar after = (Calendar) calendar.clone(); after.add(Calendar.SECOND, s); String outAfter = format.format(after.getTime()); return outAfter; } }
只给日期类,通常还有很多类型的util,百度都是有现成的,看一下就是自己的了
三 核心部分 ExcelUtil.java
import com.alibaba.excel.EasyExcelFactory; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.Sheet; import lombok.Data; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Slf4j public class ExcelUtil { private static Sheet initSheet; static { initSheet = new Sheet(1, 0); initSheet.setSheetName("sheet"); //设置自适应宽度 initSheet.setAutoWidth(Boolean.TRUE); } /** * 读取少于1000行数据 * @param filePath 文件绝对路径 * @return */ public static List<Object> readLessThan1000Row(String filePath){ return readLessThan1000RowBySheet(filePath,null); } /** * 读小于1000行数据, 带样式 * filePath 文件绝对路径 * initSheet : * sheetNo: sheet页码,默认为1 * headLineMun: 从第几行开始读取数据,默认为0, 表示从第一行开始读取 * clazz: 返回数据List<Object> 中Object的类名 */ public static List<Object> readLessThan1000RowBySheet(String filePath, Sheet sheet){ if(!StringUtils.hasText(filePath)){ return null; } sheet = sheet != null ? sheet : initSheet; InputStream fileStream = null; BufferedInputStream bufferedInputStream=null; try { fileStream = new FileInputStream(filePath); bufferedInputStream= new BufferedInputStream(fileStream); return EasyExcelFactory.read(bufferedInputStream, sheet); } catch (FileNotFoundException e) { log.info("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(fileStream != null){ fileStream.close(); } } catch (IOException e) { log.info("excel文件读取失败, 失败原因:{}", e); } } return null; } /** * 读大于1000行数据 * @param filePath 文件觉得路径 * @return */ public static List<Object> readMoreThan1000Row(String filePath){ return readMoreThan1000RowBySheet(filePath,null); } /** * 读大于1000行数据, 带样式 * @param filePath 文件觉得路径 * @return */ public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet){ if(!StringUtils.hasText(filePath)){ return null; } sheet = sheet != null ? sheet : initSheet; InputStream fileStream = null; try { fileStream = new FileInputStream(filePath); ExcelListener excelListener = new ExcelListener(); EasyExcelFactory.readBySax(fileStream, sheet, excelListener); return excelListener.getDatas(); } catch (FileNotFoundException e) { log.error("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(fileStream != null){ fileStream.close(); } } catch (IOException e) { log.error("excel文件读取失败, 失败原因:{}", e); } } return null; } /** * 生成excle * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx * @param data 数据源 * @param head 表头 */ public static void writeBySimple(String filePath, List<List<Object>> data, List<String> head){ writeSimpleBySheet(filePath,data,head,null); } /** * 生成excle * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx * @param data 数据源 * @param sheet excle页面样式 * @param head 表头 */ public static void writeSimpleBySheet(String filePath, List<List<Object>> data, List<String> head, Sheet sheet){ sheet = (sheet != null) ? sheet : initSheet; if(head != null){ List<List<String>> list = new ArrayList<>(); head.forEach(h -> list.add(Collections.singletonList(h))); sheet.setHead(list); } OutputStream outputStream = null; ExcelWriter writer = null; try { outputStream = new FileOutputStream(filePath); writer = EasyExcelFactory.getWriter(outputStream); writer.write1(data,sheet); } catch (FileNotFoundException e) { log.error("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(writer != null){ writer.finish(); } if(outputStream != null){ outputStream.close(); } } catch (IOException e) { log.error("excel文件导出失败, 失败原因:{}", e); } } } /** * 生成excle * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx * @param data 数据源 */ public static void writeWithTemplate(String filePath, List<? extends BaseRowModel> data){ writeWithTemplateAndSheet(filePath,data,null); } /** * 生成excle * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx * @param data 数据源 * @param sheet excle页面样式 */ public static void writeWithTemplateAndSheet(String filePath, List<? extends BaseRowModel> data, Sheet sheet){ if(CollectionUtils.isEmpty(data)){ return; } sheet = (sheet != null) ? sheet : initSheet; sheet.setClazz(data.get(0).getClass()); OutputStream outputStream = null; ExcelWriter writer = null; try { outputStream = new FileOutputStream(filePath); writer = EasyExcelFactory.getWriter(outputStream); writer.write(data,sheet); } catch (FileNotFoundException e) { log.error("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(writer != null){ writer.finish(); } if(outputStream != null){ outputStream.close(); } } catch (IOException e) { log.error("excel文件导出失败, 失败原因:{}", e); } } } /** * 生成多Sheet的excle * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx * @param multipleSheelPropetys */ public static void writeWithMultipleSheel(String filePath,List<MultipleSheelPropety> multipleSheelPropetys){ if(CollectionUtils.isEmpty(multipleSheelPropetys)){ return; } OutputStream outputStream = null; ExcelWriter writer = null; try { outputStream = new FileOutputStream(filePath); writer = EasyExcelFactory.getWriter(outputStream); for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) { Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet; if(!CollectionUtils.isEmpty(multipleSheelPropety.getData())){ sheet.setClazz(multipleSheelPropety.getData().get(0).getClass()); } writer.write(multipleSheelPropety.getData(), sheet); } } catch (FileNotFoundException e) { log.error("找不到文件或文件路径错误, 文件:{}", filePath); }finally { try { if(writer != null){ writer.finish(); } if(outputStream != null){ outputStream.close(); } } catch (IOException e) { log.error("excel文件导出失败, 失败原因:{}", e); } } } /*********************匿名内部类开始,可以提取出去******************************/ @Data public static class MultipleSheelPropety{ private List<? extends BaseRowModel> data; private Sheet sheet; } /** * 解析***, * 每解析一行会回调invoke()方法。 * 整个excel解析结束会执行doAfterAllAnalysed()方法 * * @author: chenmingjian * @date: 19-4-3 14:11 */ @Getter @Setter public static class ExcelListener extends AnalysisEventListener { private List<Object> datas = new ArrayList<>(); /** * 逐行解析 * object : 当前行的数据 */ @Override public void invoke(Object object, AnalysisContext context) { //当前行 // context.getCurrentRowNum() if (object != null) { datas.add(object); } } /** * 解析完所有数据后会调用该方法 */ @Override public void doAfterAllAnalysed(AnalysisContext context) { //解析结束销毁不用的资源 } } /************************匿名内部类结束,可以提取出去***************************/ }
代码58行,我改成了BufferedInputStream,不改就会抛出异常,无法正常工作,也就说最好都改成BufferedInputStream。
转载:https://blog.csdn.net/qq_32258777/article/details/89031479
如果模仿上述链接使用@Test进行测试的,记得标准logback.xml路径和引入相应jar
四 中场休息
通过学习ExcelUtil.java的做法,他在读的时候分了1000行数据的概念,这里我也查阅了相关资料,存在是有必要的,其中的道理涉及内存释放的问题,我这种小白就不指手画脚了,大神们已经帮我们把接口写好了,直接用就行了。
五 导入Excel数据 通常都是伴随着持久化操作
导入都是毛毛雨,但是需要提示的是返回List<object>,你的pojo对象无法进行转换的的,可以采用反射的方式对数据进行转换
或者你感觉数据量不大的话,采用最老土的办法,Object对象去拿出来,再强制转换
这里需要注意的时候,既然是List<object>那就仔细看清楚了,或者来个遍历,因为Excel是有表头的,过了表头才是你需要的真正数据。</object></object>
六 导出Excel数据
模板制作
单sheet页无模型导出(最low的模型,也是最快最简单的)
//配置路径 String filePath = "C:\Users\Administrator\Desktop\applicantor.xlsx"; List<List<Object>> data = new ArrayList<>(); data.add(Arrays.asList("1","胡歌","男","18")); data.add(Arrays.asList("2","彭于晏","男","18")); data.add(Arrays.asList("3","霍建华","男","18")); data.add(Arrays.asList("4","乔碧罗","女","18")); List<String> head = Arrays.asList("序号", "姓名", "性别","年龄"); ExcelUtil.writeBySimple(filePath,data,head);
单sheet页模型映射导出
import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.metadata.BaseRowModel; import lombok.Data; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) @Data//这就是使用lombok的好处,主要是快捷 public class TableHeaderModel extends BaseRowModel { /** * value: 表头名称 * index: 列的号, 0表示第一列 */ @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄",index = 1) private int age; @ExcelProperty(value = "学校",index = 2) private String school; }
String filePath = "C:\Users\Administrator\Desktop\applicantor.xlsx"; ArrayList<TableHeaderExcelProperty> data = new ArrayList<>(); TableHeaderModel tableHeaderExcelProperty = new TableHeaderExcelProperty(); tableHeaderExcelProperty.setName("cmj" + i); tableHeaderExcelProperty.setAge(22 + i); tableHeaderExcelProperty.setSchool("清华大学" + i); data.add(tableHeaderExcelProperty); ExcelUtil.writeWithTemplate(filePath,data);
多sheet页模型导出
模型不变更换方法
ArrayList<ExcelUtil.MultipleSheelPropety> list1 = new ArrayList<>(); for(int j = 1; j < 4; j++){ ArrayList<TableHeaderExcelProperty> list = new ArrayList<>(); for(int i = 0; i < 4; i++){ TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty(); tableHeaderExcelProperty.setName("cmj" + i); tableHeaderExcelProperty.setAge(22 + i); tableHeaderExcelProperty.setSchool("清华大学" + i); list.add(tableHeaderExcelProperty); } Sheet sheet = new Sheet(j, 0); sheet.setSheetName("sheet" + j); ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety(); multipleSheelPropety.setData(list); multipleSheelPropety.setSheet(sheet); list1.add(multipleSheelPropety); } ExcelUtil.writeWithMultipleSheel("C:\Users\Administrator\Desktop\applicantor.xlsx",list1); //这是直接用别人写的了
多表头模型导出
import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.metadata.BaseRowModel; import lombok.Data; import org.springframework.util.Assert; import java.math.BigDecimal; @Data public class TaxVerificationOutEO extends BaseRowModel { @ExcelProperty(value = {"帐套编码","帐套编码"},index = 0) private String organizeId; @ExcelProperty(value = {"帐套名称","帐套名称"},index = 1) private String organizeName; @ExcelProperty(value = {"税款所属期","税款所属期"},index = 2) private String verificationDate; @ExcelProperty(value={ "上期留抵税额","申报值"},index = 3) private BigDecimal basisTax; @ExcelProperty(value = {"上期留抵税额","差异"},index = 4) private BigDecimal basisTaxDiff; @ExcelProperty(value = {"本期销项","申报值"},index = 5) private BigDecimal outputTax; @ExcelProperty(value = {"本期销项","差异"},index = 6) private BigDecimal outputTaxDiff; @ExcelProperty(value = {"本期进项","申报值"},index = 7) private BigDecimal inputTax; @ExcelProperty(value = {"本期进项","差异"},index = 8) private BigDecimal inputTaxDiff; @ExcelProperty(value = {"进项转出","申报值"},index = 9) private BigDecimal inputTransfer; @ExcelProperty(value ={"进项转出", "差异"},index = 10) private BigDecimal inputTransferDiff; @ExcelProperty(value = {"本期留抵税额","申报值"},index = 11) private BigDecimal taxResult; @ExcelProperty(value = {"本期留抵税额","差异"},index = 12) private BigDecimal taxResultDiff; }
七 总结
在阿里开发这款Excel导入导出,性能上可以说中上等,我用过POI,也用过JXL,相比之下,这款更适合自定义表格,一个pojo对象对应一个模板。
它最主要的强大地方就是可以根据自己的喜好去涉及模板属性,颜色,字体,背景色,读写高效。还可以插入图片,图片支持很多,Base64(二维码),URL都可以。
Java的反射可以去了解一下,方便我们可以看懂它的各种注解
下面链接详细解释了注解的作用:
https://blog.csdn.net/sinat_32366329/article/details/103109058
小白一枚,不喜勿喷