easypoi导入excel

171 阅读1分钟

easypoi导入excel

官网:easypoi.mydoc.io/

导入依赖

<dependencies>
    <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>
</dependencies>

书写实体类

@ExcelTarget("users")//实体描述
public class UserBean {
    @Excel(name = "编号")//该属性对应列的名称
    private Integer id;
    @Excel(name = "用户名")
    private String userName;
    @Excel(name = "密码")
    private String pwd;
    @Excel(name = "生日")
    private String birthday;
    @Excel(name = "电话")
    private String phone;
}

书写controller

package com.project.controller;
​
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.word.entity.params.ExcelListEntity;
import com.project.bean.UserBean;
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 java.util.List;
​
@RestController
@RequestMapping("excel")
public class ExcelController {
​
    @RequestMapping("add")
    public List<UserBean> add(@RequestParam("excelFile") MultipartFile mf) throws Exception {
        //定义导入设置
        ImportParams ims=new ImportParams();
//        //定义标题栏占几行
        ims.setTitleRows(1);
        //设置表头占几行
        ims.setHeadRows(1);
        //设置读取第几个选项卡内容
        ims.setSheetNum(1);
​
        //将上传excel文件源,转为集合。第一个参数为上传文件读取流。
        //第二个参数为集合存放元素类模板
         //第三个参数为导入设置对象
        List<UserBean> list=ExcelImportUtil.importExcel(mf.getInputStream(),UserBean.class,ims);
        return list;
    }
}

书写html

<form action="/excel/add" method="post" enctype="multipart/form-data">
    请选择excel:<input type="file" name="excelFile"><br>
    <input type="submit" value="导入">
</form>

书写application.yml

spring:
  servlet:
    multipart:
      max-file-size: 20MB
      max-request-size: 100MB