SpringBoot学习之easyexcel导出和写入Excel(三)

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

一、加入我们需要的easyexcel依赖

SpringBoot学习之easyexcel导出和写入Excel(三)_第1张图片

我们项目还用了其他依赖,我把我的pom文件全部贴在下面,读者自行根据需要取舍



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.3.RELEASE
         
    
    com.xu
    easyexcel
    0.0.1-SNAPSHOT
    easyexcel
    Demo project for Spring Boot

    
        UTF-8
        UTF-8
        1.8
        2.9.2
        2.9.2
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
         
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            junit
            junit
            4.12
            
            test
        

        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.1.0
        

        
        
            io.springfox
            springfox-swagger-ui
            ${swagger-ui.version}
        

        
        
            io.springfox
            springfox-swagger2
            ${swagger2.version}
            
                
                    io.swagger
                    swagger-annotations
                
                
                    io.swagger
                    swagger-models
                
            
        

        
            io.swagger
            swagger-annotations
            1.5.21
        

        
            io.swagger
            swagger-models
            1.5.21
        

        
        
            com.alibaba
            druid
            1.0.29
        

        
        
            mysql
            mysql-connector-java
            5.1.38
        

        
            org.projectlombok
            lombok
            1.16.16
        

        
            com.alibaba
            fastjson
            1.2.46
        

        
        
            org.springframework
            springloaded
            1.2.8.RELEASE
            provided
        

        
            org.springframework.boot
            spring-boot-devtools
            true
        

        
        
            com.alibaba
            easyexcel
            1.1.2-beta4
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


二、定义我们的POJO

我们如果读Excel文件或者写入Excel,我们就需要先定义一个模型对应我们的Excel表格数据

SpringBoot学习之easyexcel导出和写入Excel(三)_第2张图片

package com.jwell.classifiedProtection.entry.excel;

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

/**
 * 

* 系统 *

* * @author RonnieXu * @since 2019-08-02 */ @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; }

三、定义我们的监听器和导入导出方法

我们定义了一个导出导入工具类,这个类需要一个导入导出的监听器,监听器如下

SpringBoot学习之easyexcel导出和写入Excel(三)_第3张图片

package com.jwell.classifiedProtection.commons.excel;

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;

@Slf4j
public class ExcelListener extends AnalysisEventListener {

    private List 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 getRows() {

        return rows;
    }

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

}

导入导出类ExcelUtils中有三个方法,导入方法、导出方法和下载方法导出文件方法【这个方法不需要的可以不用理会】

SpringBoot学习之easyexcel导出和写入Excel(三)_第4张图片

package com.jwell.classifiedProtection.commons.excel;

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.jwell.classifiedProtection.entry.excel.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;

@Slf4j
public class ExcelUtils {


    /**
     * @param is   导入文件输入流
     * @param clazz Excel实体映射类
     * @return
     */
    public static  List readExcel(InputStream is, final Class clazz){

        List 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 data){

        BufferedOutputStream bos= null;
        try {
            bos = new BufferedOutputStream(os);
            ExcelWriter writer = new ExcelWriter(bos, ExcelTypeEnum.XLSX);
            //写第一个sheet, sheet1  数据全是List 无模型映射关系
            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 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 responseEntity = new ResponseEntity(byteOutPutStream.toByteArray(), headers, HttpStatus.CREATED);
            return responseEntity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 这是你最熟悉的老朋友Main方法,哈哈哈
     * @param args
     */
    public static void main(String[] args) {
        //1.导入Excel
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("c:\\test\\test1.xls");
            List userExcelModelList = ExcelUtils.readExcel(fis, UserExcelModel.class);
            System.out.println("导入是否成功:-------------->"+"数据行数是:"+userExcelModelList.size());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //2.导出Excel
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("D:\\export.xlsx");
            //FileOutputStream fos, Class clazz, List data
            List list = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                UserExcelModel excelEntity = new UserExcelModel();
                excelEntity.setUserName("我是名字" + i);
                list.add(excelEntity);
            }
            Boolean flag = ExcelUtils.writeExcel(fos, UserExcelModel.class, list);
            System.out.println("导出是否成功:" + flag);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

四、测试导入和导出【下载导出的Excel文件】

1、导入测试

新建一个Excel文件,我的文件路径是c:\\test\\test1.xlsx

SpringBoot学习之easyexcel导出和写入Excel(三)_第5张图片

我的controller方法如下

SpringBoot学习之easyexcel导出和写入Excel(三)_第6张图片

package com.xu.easyexcel.controller;

import com.xu.easyexcel.commons.excel.ExcelUtils;
import com.xu.easyexcel.pojo.User;
import com.xu.easyexcel.pojo.excel.UserExcelModel;
import com.xu.easyexcel.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 

* 整改建议详情列表详情列表 前端控制器 *

* * @author RonnieXu * @since 2019-08-29 */ @Slf4j @Transactional(rollbackFor = Exception.class) @Api(value = "用户接口", tags = "用户接口") @RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService iUserService; @ApiOperation(value = "导入Excel表格", notes = "导入Excel表格") @RequestMapping(value = "/readExcel", method = RequestMethod.POST) public void readExcelModel() { try{ FileInputStream inputStream = new FileInputStream("c:\\test\\test1.xlsx"); List list = ExcelUtils.readExcel(new BufferedInputStream(inputStream), UserExcelModel.class); List userList = new ArrayList<>(); list.forEach(demo->{ User user = new User( demo.getUserName(), demo.getPassword(), demo.getRealName(), demo.getPhone(), demo.getEmail()); userList.add(user); }); System.out.println(list.size()); //将表格数据保存到数据库 iUserService.saveOrUpdateBatch(userList); } catch (IOException e) { e.printStackTrace(); } } @ApiOperation(value = "导出Excel表格", notes = "导出Excel表格") @RequestMapping(value = "/exprotExcel", method = RequestMethod.POST) public ResponseEntity exprotExcel() { try { List list = iUserService.list(); List dataList = new ArrayList<>(); list.forEach(user->{ UserExcelModel userExcelModel = new UserExcelModel( user.getUserName(), user.getPassword(), user.getRealName(), user.getPhone(), user.getEmail()); dataList.add(userExcelModel); }); System.out.println(dataList.size()); //数据写入到字节流 ByteArrayOutputStream bos = new ByteArrayOutputStream(); boolean flag = ExcelUtils.writeExcel(bos, UserExcelModel.class, dataList); //下载文件 String fileName = "下载整改建议.xls"; log.info("开始下载导出的Excel文件"); return ExcelUtils.downloadExcel(fileName, bos); } catch (Exception e) { e.printStackTrace(); } return null; } }

打开swagger,点击测试,可以看到成功读取到了Excel文件的数据,并成功插入到数据库

SpringBoot学习之easyexcel导出和写入Excel(三)_第7张图片

SpringBoot学习之easyexcel导出和写入Excel(三)_第8张图片

2、导出测试【下载导出文件】

SpringBoot学习之easyexcel导出和写入Excel(三)_第9张图片

点击swagger方法测试或者直接在浏览器中输入http://localhost/user/exprotExcel,可以看到成下载了导出文件

【说明:在swagger中下载的文件名是乱码,暂时不知道哪里出了问题,后续知道原因再补充说明】

SpringBoot学习之easyexcel导出和写入Excel(三)_第10张图片

打开可以看到的确成功从把数据库数据导出并成功下载了

SpringBoot学习之easyexcel导出和写入Excel(三)_第11张图片

谢谢读者支持,下次再见!

你可能感兴趣的:(SpringBoot)