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依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath />
    </parent>
 
    <!-- 设jdk版本1.8和项目编码格式UTF-8 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <!-- 集成easypoi组件 .导出excel http://easypoi.mydoc.io/ -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>
        
        <!-- 这个依赖相当于上面 easypoi-base、easypoi-web、easypoi-annotation这3个依赖,可以引入上面3个依赖,也可以引入下面这一个,两个方案二选一-->
    <!--     <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-spring-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency> -->
 
 
        <!-- 集成springboot web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 集成springboot test组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 集成lombok 框架 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- 文件上传组件 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--阿里巴巴 fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
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;
 
/**
 * <pre>
 * &#64;author cao_wencao
 * &#64;date 2018年12月13日 下午4:50:18
 * </pre>
 */
@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<Map<String, Object>> 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<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null)
            ;
        downLoadExcel(fileName, response, workbook);
    }
 
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> 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 <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows,
            Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> 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;
 
/**
 * <pre>
 * &#64;author cao_wencao
 * &#64;date 2018年12月13日 下午5:37:17
 * </pre>
 */
@Service
public class UserService {
    
    public List<User> findAll() {
        List<User> listAll = Lists.newArrayList();
        List<User> 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;
 
/**
 * <pre>
 * &#64;author cao_wencao
 * &#64;date 2018年12月13日 下午6:16:59
 * </pre>
 */
@RestController
@RequestMapping("/excel/export")
public class ExcelExportController {
    @Autowired
    private UserService userService;
 
    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response) {
        System.out.println(1);
        // 模拟从数据库获取需要导出的数据
        List<User> 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;
 
/**
 * <pre>
 * &#64;author cao_wencao
 * &#64;date 2018年12月13日 下午6:17:10
 * </pre>
 */
@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<User> result = ExcelImportUtil.importExcelMore(file.getInputStream(), User.class,
                    importParams);
            List<User> 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;
 
/**
 * <pre>
 * @author cao_wencao
 * @date 2018年12月13日 下午4:38:24
 * </pre>
 */
@SpringBootApplication
public class SpringBootEasyPoiApp {
 
    /**
     * <pre>  
     * @author cao_wencao
     * @param args
     * </pre>  
     */
    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 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值