vue3+ts实现导入excel文件功能

在实际应用中,我们经常会有导入Excel或者上传图片的需求,
下面我们搭配使用element-plus中的上传组件实现导入Excel功能

<el-form class="drawer-multiColumn-form" label-width="100px">
        <el-form-item label="模板下载 :">
          <el-button type="primary" icon="download" @click="downloadTemp"
            >点击下载</el-button
          >
        </el-form-item>
        <el-form-item label="文件上传:">
          <el-upload
            action=""
            class="upload-demo"
            drag
            accept=".xlsx, .xls"
            :on-exceed="exceedFile"
            :on-error="handleError"
            :on-success="handleSuccess"
            :http-request="uploadExcel"
            :before-upload="beforeUPload"
            :show-file-list="true"
            :limit="excelLimit">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处,或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">请上传 .xls , .xlsx 标准格式文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

上面整体的样式就出来了,此时可以参考element-plus中上传组件的API,下面是一些在上传前的校验

// 文件上传之前判断
const beforeUPload = (file: any) => {
    
    
  const isExcel =
    file.type === 'application/vnd.ms-excel' ||
    file.type ===
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isLt2M = file.size / 1024 / 1024 < 20;
  if (!isExcel)
    ElNotification({
    
    
      title: '温馨提示',
      message: '上传文件只能是 xls / xlsx 格式!',
      type: 'warning',
    });
  if (!isLt2M)
    ElNotification({
    
    
      title: '温馨提示',
      message: '上传文件大小不能超过 20MB!',
      type: 'warning',
    });
  return isExcel && isLt2M;
};
// 文件数超出提示
const exceedFile = () => {
    
    
  ElNotification({
    
    
    title: '温馨提示',
    message: '最多只能上传一个文件!',
    type: 'warning',
  });
};
// 上传错误提示
const handleError = () => {
    
    
  ElNotification({
    
    
    title: '温馨提示',
    message: '导入数据失败,请您重新上传!',
    type: 'error',
  });
};

//上传成功提示
const handleSuccess = () => {
    
    
  ElNotification({
    
    
    title: '温馨提示',
    message: '导入数据成功!',
    type: 'success',
  });
};

最后我们来写文件上传时的方法

// 文件上传
const uploadExcel = async (param: any) => {
    
    
  let fileFormData = new FormData();
  fileFormData.append('file', param.file, param.file.name);
  const res =await importUrl(fileFormData);
  if (res.code !== 0) return  param.onError();
  dialogVisible.value = false;
};

这样,我们一个导入功能就完成了,下面会再整理一篇导出功能的博客出来,敬请期待!

猜你喜欢

转载自blog.csdn.net/Rice_w/article/details/125710774
今日推荐