SpringBoot | 第十三章:springboot集成easypoi实现Excel导入导出

https://blog.csdn.net/Thinkingcao/article/details/85005930

easypoi官方文档:http://easypoi.mydoc.io/

 借鉴博客:https://blog.csdn.net/qq_37598011/article/details/80918565

1. 前传
  1.1 前言

  easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员 就可以方便的写出Excel导出,Excel模板导出,Excel导    入,Word模板导出,通过简单的注解和模板 语言(熟悉的表达式语法),完成以前复杂的写法

2. 功能
Excel自适应xls和xlsx两种格式,word只支持docx模式

1.Excel导入

注解导入
Map导入
大数据量导入sax模式
导入文件保存
文件校验
字段校验
2.Excel导出

注解导出
模板导出
html导出
3.Excel转html

4.word导出

5.pdf导出

 

3. Easypoi介绍
    Easypoi 为谁而开发

不太熟悉poi的
不想写太多重复太多的
只是简单的导入导出的
喜欢使用模板的
4. 新建SpringBoot项目,引入pom依赖


        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE
        
    

 
    
    
        UTF-8
        UTF-8
        1.8
    

 
    
        
        
            cn.afterturn
            easypoi-base
            3.2.0
        

        
            cn.afterturn
            easypoi-web
            3.2.0
        

        
            cn.afterturn
            easypoi-annotation
            3.2.0
        

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

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

        
        
            org.projectlombok
            lombok
        

        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        

        
        
            com.alibaba
            fastjson
            1.2.30
        

    

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

        

    

5. 定义需要导出的实体对象User

    补充@Setter、@Getter、@ToString这三个注解是使用Lombok插件,不知道的另行百度即可;

import java.util.Date;
 
import javax.validation.constraints.NotBlank;
 
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
 
/**
 *


 * @author cao_wencao
 * @date 2018年12月13日 下午4:50:18
 *

 */
@ExcelTarget("20")
@Setter
@Getter
@ToString
public class User implements java.io.Serializable{
    @Excel(name = "id", width=15)
    @NotBlank(message = "该字段不能为空")
    private Integer id;
 
    @Excel(name = "姓名", orderNum = "0", width=30)
    private String name;
 
    @Excel(name = "性别", replace = { "男_1", "女_2" }, orderNum = "1", width=30)
    private String sex;
 
    @Excel(name = "生日", exportFormat = "yyyy-MM-dd",  orderNum = "2", width=30)
    private String birthday;
 
 
 
}
5. Excel导入导出工具类

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
 
//Excel导入导出工具类
public class ExcelUtils {
    public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName,
            boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }
 
    public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName,
            HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
 
    public static void exportExcel(List> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }
 
    private static void defaultExport(List list, Class pojoClass, String fileName, HttpServletResponse response,
            ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null)
            ;
        downLoadExcel(fileName, response, workbook);
    }
 
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            // throw new NormalException(e.getMessage());
        }
    }
 
    private static void defaultExport(List> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null)
            ;
        downLoadExcel(fileName, response, workbook);
    }
 
    public static List importExcel(String filePath, Integer titleRows, Integer headerRows, Class pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            // throw new NormalException(e.getMessage());
        }
        return list;
    }
 
    public static List importExcel(MultipartFile file, Integer titleRows, Integer headerRows,
            Class pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("excel文件不能为空");
        } catch (Exception e) {
            // throw new NormalException(e.getMessage());
            System.out.println(e.getMessage());
        }
        return list;
    }
 
}
6. 封装接口,定义Service,分别定义查询导出数据和保存导入数据的方法,我这个demo中就写假接口,不操作数据库,自己用的时候自行开发接口从数据库存取

import java.util.Date;
import java.util.List;
 
import org.springframework.stereotype.Service;
 
import com.google.common.collect.Lists;
import com.thinkingcao.demo.easypoi.entity.User;
 
/**
 *


 * @author cao_wencao
 * @date 2018年12月13日 下午5:37:17
 *

 */
@Service
public class UserService {
    
    public List findAll() {
        List listAll = Lists.newArrayList();
        List list = Lists.newArrayList();
        User user = new User();
        user.setId(10);
        user.setName("张三");
        user.setSex("男");
        user.setBirthday(new Date().toString());
        User user1 = new User();
        user1.setId(20);
        user1.setName("李四");
        user1.setSex("男");
        user1.setBirthday(new Date().toString());
        user.setBirthday(new Date().toString());
        User user2 = new User();
        user2.setId(20);
        user2.setName("王五");
        user2.setSex("男");
        user2.setBirthday(new Date().toString());
        list.add(user);
        list.add(user1);
        list.add(user2);
        listAll.addAll(list);
        return listAll;
    }
}
7. 导出方法的Controller。ExcelExportController

import java.util.List;
 
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import com.thinkingcao.demo.easypoi.entity.User;
import com.thinkingcao.demo.easypoi.service.UserService;
import com.thinkingcao.demo.easypoi.utils.ExcelUtils;
 
/**
 *


 * @author cao_wencao
 * @date 2018年12月13日 下午6:16:59
 *

 */
@RestController
@RequestMapping("/excel/export")
public class ExcelExportController {
    @Autowired
    private UserService userService;
 
    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response) {
        System.out.println(1);
        // 模拟从数据库获取需要导出的数据
        List personList = userService.findAll();
        // 导出操作
        ExcelUtils.exportExcel(personList, "easypoi导出功能", "导出sheet1", User.class, "测试user.xls", response);
 
    }
}
8. 导入方法的Controller。ExcelImportController 

import java.io.IOException;
import java.util.List;
 
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.thinkingcao.demo.easypoi.entity.User;
 
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import lombok.extern.slf4j.Slf4j;
 
/**
 *


 * @author cao_wencao
 * @date 2018年12月13日 下午6:17:10
 *

 */
@RestController
@RequestMapping("/excel/import")
@Slf4j
public class ExcelImportController {
 
    @PostMapping("/importExcel")
    public String importExcel2(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);
        // 需要验证
        importParams.setNeedVerfiy(false);       
        
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(file.getInputStream(), User.class,
                    importParams);
            List userList = result.getList();
            for (User User : userList) {
                // System.out.println(User);
                log.info("从Excel导入数据到数据库的详细为 :{}", JSONObject.toJSONString(User));
                //TODO 将导入的数据做保存数据库操作
            }
            log.info("从Excel导入数据一共 {} 行 ", userList.size());
        } catch (IOException e) {
            log.error("导入失败:{}", e.getMessage());
        } catch (Exception e1) {
            log.error("导入失败:{}", e1.getMessage());
        }
        return "导入成功";
    }
}
9.创建启动类SpringBootEasyPoiApp

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
/**
 *


 * @author cao_wencao
 * @date 2018年12月13日 下午4:38:24
 *

 */
@SpringBootApplication
public class SpringBootEasyPoiApp {
 
    /**
     *
  
     * @author cao_wencao
     * @param args
     *
 
     */
    public static void main(String[] args) {
        SpringApplication.run(SpringBootEasyPoiApp.class, args);
    }
 
}
10.创建aplication.yml文件,定义端口

server:
  port: 8998
11.结果

Excel导入接口
     接口地址:http://127.0.0.1:8998/excel/import/importExcel

     

Excel导出接口
     接口地址:http://127.0.0.1:8998/excel/export/exportExcel

     

 

简单的导入导出就这样,很简单,有其他更加丰富的功能,可以阅读作者文档:http://easypoi.mydoc.io/

 
--------------------- 
作者:自由不过一种漂泊 
来源:CSDN 
原文:https://blog.csdn.net/Thinkingcao/article/details/85005930 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(java)