如何在Vue+SpringBoot应用中导入导出excel表

96 阅读1分钟

如何在Vue+SpringBoot应用中导入导出excel表

如何完成人超级好的项目组长给的任务

今天,人超级好的组长交给我一个任务,让我完成导入导出用户列表的功能。

QQ20251008-202829.jpg

后端

1.控制层写导入导出的接口

QQ20251008-203226.jpg

2.Service层写导入导出的具体方法

以下是导入数据的代码,要用到FastExcel读取数据后,再调用UserDao进行数据的插入

public ResponseDTO<String> importUsers(MultipartFile file){
    List<UserImportForm> dataList;
    try{
        dataList = FastExcel.read(file.getInputStream()).head(UserImportForm.class)
                .sheet()
                .doReadSync();
        for(UserImportForm userImportForm:dataList){
            UserEntity userEntity = SmartBeanUtil.copy(userImportForm,UserEntity.class);
            userDao.insert(userEntity);
        }
    }catch(IOException e){
        log.error(e.getMessage(),e);
        throw new BusinessException("数据格式存在问题,无法读取");
    }
    if(CollectionUtils.isEmpty(dataList)){
        return ResponseDTO.userErrorParam("数据为空");
    }
    return ResponseDTO.okMsg("成功导入"+dataList.size()+"条,具体数据为:"+ JSON.toJSONString(dataList));
}
3.FastExcel

下篇文章写FastExcel

前端

1.分为三步

image.png

2.第一步下载模板
<a-button @click="downloadExcel"> <download-outlined />第一步:下载模板</a-button>

直接将excel表单放在static文件夹下就可以了,前端就可以直接下载表单

function downloadExcel(){
  window.open('http://localhost:1024/user.xlsx');
}
3.第二步选择文件

image.png

4.第三步开始导入
<a-button @click="onImportUsers">
  <ImportOutlined />
  第三步:开始导入
</a-button>

中间调用后端提供的接口/user/importUsers就可

async function onImportUsers(){
  const formData = new FormData();
  fileList.value.forEach((file)=>{
    formData.append('file',file.originFileObj);
  });
  SmartLoading.show();
  try{
    let res = await userApi.importUsers(formData);
    message.success(res.msg);
  }catch(e){
    smartSentry.captureError(e);
  }finally {
    SmartLoading.hide();
  }
}