Java使用EasyExcel实现批量导入

导读:本篇文章讲解 Java使用EasyExcel实现批量导入,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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

第一步:引入jar包

<!-- excel工具框架 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>

<!--easyexcel解析excell-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>1.0.3</version>
</dependency>

第二步:读取工具类封装

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<T> List<T> getExcelContent(InputStream in, Class<T> tClass){
        List<T> excelPropertyIndexModelList = new ArrayList<>();
        try {
            AnalysisEventListener<T> listener = new AnalysisEventListener<T>() {
                @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<? extends BaseRowModel>) 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实现批量导入

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

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

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

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

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

});

}

好了,以上就是使用方法了。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/97034.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!