package com.ycl.utils.poi; import com.alibaba.excel.EasyExcelFactory; import com.alibaba.excel.util.IoUtils; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.google.common.collect.Lists; import com.ycl.dataListener.EasyExcelListener; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class EasyExcelImportUtils { /** * 动态获取全部列和数据体 * [stream, parseRowNumber] * @return {@link List< Map< String, String>>} * @throws */ public static List> parseExcelToData(byte[] stream, Integer parseRowNumber) { EasyExcelListener readListener = new EasyExcelListener(); EasyExcelFactory.read(new ByteArrayInputStream(stream)).registerReadListener(readListener).headRowNumber(parseRowNumber).sheet(0).doRead(); List> headList = readListener.getHeadList(); if(CollectionUtils.isEmpty(headList)){ throw new RuntimeException("Excel表头不能为空"); } List> dataList = readListener.getDataList(); if(CollectionUtils.isEmpty(dataList)){ throw new RuntimeException("Excel数据内容不能为空"); } //获取头部,取最后一次解析的列头数据 Map excelHeadIdxNameMap = headList.get(headList.size() -1); //封装数据体 List> excelDataList = Lists.newArrayList(); for (Map dataRow : dataList) { Map rowData = new LinkedHashMap<>(); excelHeadIdxNameMap.entrySet().forEach(columnHead -> { rowData.put(columnHead.getValue(), dataRow.get(columnHead.getKey())); }); excelDataList.add(rowData); } return excelDataList; } /** * 返回导入的所有数据 * [file] * @return {@link List< Map< String, String>>} * @throws */ public static List> makeData(MultipartFile file){ InputStream inputStream = null;//转换成输入流 try { inputStream = file.getInputStream(); } catch (IOException e) { e.printStackTrace(); } byte[] stream = new byte[0]; try { stream = IoUtils.toByteArray(inputStream); } catch (IOException e) { e.printStackTrace(); } if(stream == null || stream.length == 0){ return null; } List> dataList = parseExcelToData(stream, 1);//从动态获取全部列和数据体,默认从第一行开始解析数据 try { if(inputStream != null){ inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } return dataList; } }