參考EasyPoi官網,需要引入
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
</dependency>
定義實體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<User> 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目錄下