Java使用EasyExcel实现批量导入

EasyExcel是阿里下的开源产品,基于poi进行的开发,相比于其他的解析方式不要太6。接下来就是使用的方式

 

第一步:引入jar包



    com.alibaba
    easyexcel
    1.0.3

第二步:读取工具类封装

package com.edu.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import org.apache.poi.EmptyFileException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.util.IOUtils;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;

/**
 *@ClassName EasyExcelUtil
 *@Description easyExcel操作excel工具类
 *@Auther William
 *@Date 2019/6/5 11:35
 *@Version 1.0
 */
public class EasyExcelUtil {
    /**
     * @param in 文件输入流
     * @param customContent
     *           自定义模型可以在
     *           AnalysisContext中获取用于监听者回调使用
     * @param eventListener 用户监听
     * @throws IOException
     * @throws EmptyFileException
     * @throws InvalidFormatException
     */
    public static ExcelReader getExcelReader(InputStream in, Object customContent,AnalysisEventListener eventListener) throws EmptyFileException, IOException, InvalidFormatException {
        // 如果输入流不支持mark/reset,需要对其进行包裹
        if (!in.markSupported()) {
            in = new PushbackInputStream(in, 8);
        }
        // 确保至少有一些数据
        byte[] header8 = IOUtils.peekFirst8Bytes(in);
        ExcelTypeEnum excelTypeEnum = null;
        if (NPOIFSFileSystem.hasPOIFSHeader(header8)) {
            excelTypeEnum = ExcelTypeEnum.XLS;
        }
        if (DocumentFactoryHelper.hasOOXMLHeader(in)) {
            excelTypeEnum = ExcelTypeEnum.XLSX;
        }
        if (excelTypeEnum != null) {
            return new ExcelReader(in, excelTypeEnum, customContent, eventListener);
        }
        throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");

    }

    /**
     * @param in 文件输入流
     * @param customContent
     *           自定义模型可以在
     *           AnalysisContext中获取用于监听者回调使用
     * @param eventListener 用户监听
     * @param trim  是否对解析的String做trim()默认true,用于防止 excel中空格引起的装换报错。
     * @throws IOException
     * @throws EmptyFileException
     * @throws InvalidFormatException
     */
    public static ExcelReader getExcelReader(InputStream in, Object customContent,
                                             AnalysisEventListener eventListener, boolean trim)
            throws EmptyFileException, IOException, InvalidFormatException {
        // 如果输入流不支持mark/reset,需要对其进行包裹
        if (!in.markSupported()) {
            in = new PushbackInputStream(in, 8);
        }

        // 确保至少有一些数据
        byte[] header8 = IOUtils.peekFirst8Bytes(in);
        ExcelTypeEnum excelTypeEnum = null;
        if (NPOIFSFileSystem.hasPOIFSHeader(header8)) {
            excelTypeEnum = ExcelTypeEnum.XLS;
        }
        if (DocumentFactoryHelper.hasOOXMLHeader(in)) {
            excelTypeEnum = ExcelTypeEnum.XLSX;
        }
        if (excelTypeEnum != null) {
            return new ExcelReader(in, excelTypeEnum, customContent, eventListener, trim);
        }
        throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
    }


    /*
     *@Description: 读取Excel文件内容
     *@param in excel文件流
     *@param tClass 对应excel实体bean
     *@return: 对应excel实体bean的list
     *@Author:  William
     *@Date:  2019/6/5 13:24
     */
    public static List getExcelContent(InputStream in, Class tClass){
        List excelPropertyIndexModelList = new ArrayList<>();
        try {
            AnalysisEventListener listener = new AnalysisEventListener() {
                @Override
                public void invoke(T excelPropertyIndexModel, AnalysisContext analysisContext) {
                    excelPropertyIndexModelList.add(excelPropertyIndexModel);
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    //读取之后的操作
                }
            };
            ExcelReader excelReader = EasyExcelUtil.getExcelReader(in, null, listener);
            // 第二个参数为表头行数,按照实际设置
            excelReader.read(new Sheet(1, 1, (Class) tClass));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return excelPropertyIndexModelList;
    }
}

第三步:封装excel对应的实体bean(这一步要注意,每一个字段跟表格要对应起来)

package com.edu.common.pojo;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.edu.common.utils.EasyExcelUtil;

/**
 *@ClassName ExcelImportUserInfo
 *@Description 批量导入用户信息模板bean
 *@Auther William
 *@Date 2019/6/5 13:32
 *@Version 1.0
 */
public class ExcelImportUserInfo extends BaseRowModel{
    @ExcelProperty(value = "用户名", index = 0)
    private String userName;

    @ExcelProperty(value = "用户角色", index = 1)
    private String userRole;

    @ExcelProperty(value = "用户姓名", index = 2)
    private String userId;

    @ExcelProperty(value = "用户密码", index = 3)
    private String password;

    @ExcelProperty(value = "性别", index = 4)
    private String sex;

    @ExcelProperty(value = "用户年级", index = 5)
    private String gradeId;

    @ExcelProperty(value = "用户学校", index = 6)
    private String schoolId;

    @ExcelProperty(value = "用户状态", index = 7)
    private String userStatus;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserRole() {
        return userRole;
    }

    public void setUserRole(String userRole) {
        this.userRole = userRole;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getGradeId() {
        return gradeId;
    }

    public void setGradeId(String gradeId) {
        this.gradeId = gradeId;
    }

    public String getSchoolId() {
        return schoolId;
    }

    public void setSchoolId(String schoolId) {
        this.schoolId = schoolId;
    }

    public String getUserStatus() {
        return userStatus;
    }

    public void setUserStatus(String userStatus) {
        this.userStatus = userStatus;
    }
    @Override
    public String toString() {
        return "ExcelImportUserInfo{" +
                "userName='" + userName + '\'' +
                ", userRole='" + userRole + '\'' +
                ", userId='" + userId + '\'' +
                ", password='" + password + '\'' +
                ", sex='" + sex + '\'' +
                ", gradeId='" + gradeId + '\'' +
                ", schoolId='" + schoolId + '\'' +
                ", userStatus='" + userStatus + '\'' +
                '}';
    }

    
}

对应的excel表格

Java使用EasyExcel实现批量导入_第1张图片

测试方法:(测试方法基于jdk1.8,如果1.7自己换成for循环吧)

public static void main(String[] args) throws Exception {

InputStream in = new FileInputStream("E://aaa.xlsx");
  //读取的工具类可以根据自己需要封装
  //我这边是需要List集合所以封装了集合

List excelContentList = EasyExcelUtil.getExcelContent(in, ExcelImportUserInfo.class); excelContentList.forEach(excelPropertyIndexModel -> {

           System.out.println(excelPropertyIndexModel.toString());

});

}

 

好了,以上就是使用方法了。如果有什么问题可以联系我wx:15021801061

你可能感兴趣的:(开发常用工具类)