后端代码:
引入依赖:

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>easyexcel</artifactId>
   <version>3.0.5</version>
</dependency>

后端实体类:

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDate;
import java.util.Date;

@Getter
@Setter
public class ExportVo {

   @ExcelProperty("用户名")
   private String userName;

   @ExcelProperty("日期")
   private Date createTime;
}

控制逻辑:这里是导入了,获取了实体类的信息然后再进行输出。

@PostMapping("/importTest")
public void importTest(@RequestParam(value = "file")MultipartFile file,HttpServletResponse response)throws Exception
{
    if(file.isEmpty()){
        return;
    }
    List<ExportVo> result = new ArrayList<>();
    EasyExcel.read(file.getInputStream(),ExportVo.class,new PageReadListener<ExportVo>(dataList -> {
        result.addAll(dataList);
    })).sheet().doRead();
    for(ExportVo vo:result){
        System.out.println(vo.getUserName() + "-" + vo.getCreateTime());
    }

}

效果示例:可以看到后端输出了字符串和日期。

前端代码:
添加按钮

 <el-upload class="upload-demo" ref="upload" action="#" :on-change="changeFile" :file-list="fileList" :auto-upload="false" :limit ="1">
          <el-button slot="trigger" size="small" type="primary">选取xlsx</el-button>
       </el-upload>

上传事件changeFile上传到后端:

 changeFile(file){
              let formData = new FormData()
              formData.append('file',file.raw)
              let url = 'http://127.0.0.1:9998/demo/importTest'
              axios({
                method:'post',
                url:url,
                data: formData,
                headers:{
                    "Content-Type":"multipart/form-data"
                },
                timeout:20000,
                responseType:'blob'
              }).then(res => {
                let blob = new Blob([res.data])
              })
           },

效果图:即可上传成功


小全栈工程师小鹿
4 声望0 粉丝

一个菜鸡的全干工程师......