5行Java代码实现Excel的导入导出

使 m a i n C V \color{#FF0000}{快速使用:只需修改第四步main方法中的前三行代码,其他直接CV大法即可;}

前言:easyexcel是阿里巴巴旗下开源项目,主要用于Excel文件的导入和导出处理,今天我们利用SpringBoot和easyexcel实战演示如何导出和写入Excel文件。
一、导入pom文件中的依赖

<!-- alibaba的easyexcel -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>1.1.2-beta4</version>
</dependency>

二、定义我们的pojo

package com.xhy.xczx.pojo;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.*;

/**
 * 〈Excel实体类〉
 *
 * @author Barrett
 * @version 1.0.0
 * @time 2020/2/4
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class UserExcelModel extends BaseRowModel {

    private static final long serialVersionUID = 1L;

    @ExcelProperty(value = "用户名", index = 0)
    private String userName;

    @ExcelProperty(value = "密码", index = 1)
    private String password;

    @ExcelProperty(value = "真实姓名", index = 2)
    private String realName;

    @ExcelProperty(value = "电话号码", index = 3)
    private String phone;

    @ExcelProperty(value = "邮箱地址", index = 4)
    private String email;

    private String roleType;

    private Integer departmentId;

    private String remark;

}

三、定义我们的监听器

package com.xhy.xczx.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 〈监听器〉
 *
 * @author Barrett
 * @version 1.0.0
 * @time 2020/2/4
 */
@Slf4j
public class ExcelListener<T extends BaseRowModel> extends AnalysisEventListener<T> {

    private List<T> rows = new ArrayList<>();

    /**
     * object是每一行数据映射的对象
     *
     * @param object
     * @param context
     */
    @Override
    public void invoke(T object, AnalysisContext context) {
        System.out.println("当前行:" + context.getCurrentRowNum());
        System.out.println(object);
        rows.add(object);
        //根据自己业务做处理
        doSomething(object);
    }

    private void doSomething(T object) {
        //1、入库调用接口
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

        log.info("read {} rows %n", rows.size());
    }

    public List<T> getRows() {

        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

}

四、定义导入导出工具类

package com.xhy.xczx.utils;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.xhy.xczx.pojo.UserExcelModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 〈导出Excel表工具类〉
 *
 * @author Barrett
 * @version 1.0.0
 * @time 2020/2/4
 */
@Slf4j
public class ExcelUtils {


    /**
     * @param is    导入文件输入流
     * @param clazz Excel实体映射类
     * @return
     */
    public static <T extends BaseRowModel> List<T> readExcel(InputStream is, final Class<? extends BaseRowModel> clazz) {
        List<T> rowsList = null;
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(is);
            // 解析每行结果在listener中处理
            ExcelListener listener = new ExcelListener();
            ExcelReader excelReader = EasyExcelFactory.getReader(bis, listener);
            excelReader.read(new Sheet(1, 1, clazz));
            rowsList = listener.getRows();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return rowsList;
    }

    /**
     * @param os    文件输出流
     * @param clazz Excel实体映射类
     * @param data  导出数据
     * @return
     */
    public static Boolean writeExcel(OutputStream os, Class clazz, List<? extends BaseRowModel> data) {
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(os);
            ExcelWriter writer = new ExcelWriter(bos, ExcelTypeEnum.XLSX);
            //写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
            Sheet sheet1 = new Sheet(1, 0, clazz);
            writer.write(data, sheet1);
            writer.finish();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * ResponseEntity下载文件
     *
     * @param fileName
     * @param byteOutPutStream
     */
    public static ResponseEntity<byte[]> downloadExcel(String fileName, ByteArrayOutputStream byteOutPutStream) {
        //下载文件
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment",
                    new String(fileName.getBytes("GBK"), "ISO8859-1"));// 文件名称
            ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(byteOutPutStream.toByteArray(), headers, HttpStatus.CREATED);
            return responseEntity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 这是你最熟悉的老朋友Main方法,哈哈哈
     *
     * @param args
     */
    public static void main(String[] args) throws FileNotFoundException {
        //1.获取Excel表信息并导入
        FileInputStream fileInputStream = new FileInputStream("d:\\test\\import\\用户模型表-导入.xlsx");
        List<BaseRowModel> baseRowModels = ExcelUtils.readExcel(fileInputStream, UserExcelModel.class);
        //2.获取输出路径并导出Excel
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\test\\export\\用户模型表-导出.xlsx");
        Boolean aBoolean = ExcelUtils.writeExcel(fileOutputStream, UserExcelModel.class, baseRowModels);
        System.out.println("导入是否成功:-------------->" + "数据行数是:" + baseRowModels.size());
        if (aBoolean) {
            System.out.println("导出成功!!!");
        } else {
            System.out.println("导出失败!!!");
        }
    }
}

在工具类中运行main方法即可实现将本地文件导入后输出到另一个文件当中;
注意:我本地导入文件路径:D:\test\import\用户模型表-导入.xlsx
导出文件路径:D:\test\export\用户模型表-导出.xlsx

发布了134 篇原创文章 · 获赞 32 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/yang_guang3/article/details/104179428
今日推荐