SpringBoot集成EasyPoi

参考EasyPoi官网,需要引入

        
            cn.afterturn
            easypoi-spring-boot-starter
        
定义实体User
package com.wu.parker.easypoi.po;

import cn.afterturn.easypoi.excel.annotation.Excel;

import java.util.Date;

/**
 * @author: wusq
 * @date: 2018/12/15
 */

public class User {

    @Excel(name = "姓名", orderNum = "0")
    private String name;

    @Excel(name = "性别", replace = {"男_1", "女_0"}, orderNum = "1")
    private String sex;

    @Excel(name = "出生日期", exportFormat = "yyyy-MM-dd", orderNum = "2")
    private Date birthday;
    
    // 请自行添加get/set方法
}

UserController
package com.wu.parker.easypoi.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.wu.parker.common.web.BaseResult;
import com.wu.parker.easypoi.po.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author: wusq
 * @date: 2018/12/15
 */
@Api(description = "用户服务")
@RestController
@RequestMapping("/users/")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @ApiOperation("导入excel")
    @PostMapping("import-excel")
    public BaseResult importExcel(@RequestParam("file") MultipartFile file){
        BaseResult result = new BaseResult();

        try {
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            List userList = ExcelImportUtil.importExcel(file.getInputStream(), User.class, params);
            userList.forEach(o -> System.out.println(o));
        } catch (Exception e) {
            result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            result.setMessage(e.getMessage());
            log.error("导入excel{}", e.getMessage());
            e.printStackTrace();
        }

        return result;
    }
}

新建excel进行上传测试
姓名 性别 出生日期
张三 1980-01-01
李四 1982-02-02
源代码

https://github.com/wu-boy/parker
users.xlsx文件位于resources目录下

你可能感兴趣的:(Spring)