导入导出excel

该文介绍了如何使用AntDesign的a-upload-dragger组件实现拖拽上传功能,包括设置接受文件类型、清除列表、上传前的处理等。同时,文章详细阐述了如何处理后端返回的文件流进行下载,涉及到GET和POST请求,以及不同浏览器的兼容性处理。
摘要由CSDN通过智能技术生成

导入

antd——a-upload-dragger拖拽上传组件

 <a-upload-dragger
      accept=".xls, .xlsx"
      showUploadList={false}
      v-model={[this.fileList, "fileList"]}
      beforeUpload={async () => {
      this.fileList = []}}
      multiple={false}
  >
     {this.fileList.length ? (
      <>
       <p class="ant-upload-drag-icon">
         <FileExcelTwoTone twoToneColor="#00C090" />
       </p>
       <p class="ant-upload-text">{this.fileList[0].name}</p>
       <p class="ant-upload-hint">
        <a-button>重新上传</a-button>
       </p>
      </>
      ) : (
      <>
       <p class="ant-upload-drag-icon">
        <folder-outlined />
       </p>
       <p class="ant-upload-text">点击或把文件拖到这里上传</p>
       <p class="ant-upload-hint">支持格式:xls/xlsx</p>
       </>
      )}
     </a-upload-dragger>
upLoadFile: (file: any) => {
    const formData = new FormData();
    formData.append("file", file);
    return instance.post("/common/v1/employee/import/multi", formData);
},

originFileObj 属性获取原始文件 

const fileList = ref<any[]>([]);

const handleCommit = async () => {
      const file = fileList.value[0];
      if (!file) {
        return message.warn("请上传文件");
      }
      isLoading.value = true;
      const res = await api.upLoadFile(file.originFileObj).finally(() => {
        isLoading.value = false;
      });
      message.success("导入成功");
      isVisible.value = false;
      props.onRefresh?.();
};

导出

后端返回的是文件流类型

get请求,直接使用window.open

export const getShiftLogExport = (startDate: number, endDate: string) => {
  window.open(
    `/api/flocculant/v1/dryPowderLog/getShiftLogExport?startDate=${startDate}&endDate=${endDate}`,
  );
};

post请求,要在header里加东西 

  export const getDayLogExport = (
  startDate: number,
  endDate: number,
): Promise<any> => {
  return instance.get(
    `/flocculant/v1/dryPowderLog/getDayLogExport?startDate=${startDate}&endDate=${endDate}`,
    {
      responseType: 'blob',
      headers: {
        'Content-Disposition': 'attachment',
        'Content-Type': 'text/html;charset=UTF-8',
      },
    },
  );
};
   let blob = new Blob([res], { type: 'text/html;charset=UTF-8;xls' }); //这里的type为文件类型  需要与后端确认(一定要确认)
   const fileName = '班报日志.xls'; //注意后缀要与type一致
   const alink = document.createElement('a'); //创建一个a标签
   alink.download = fileName;
   alink.style.display = 'none';
   alink.href = URL.createObjectURL(blob);
   document.body.appendChild(alink);
   alink.click(); //模拟点击事件
   URL.revokeObjectURL(alink.href);
   document.body.removeChild(alink);
export async function downloadFile(url: string, name: string) {
  axios({
    timeout: apiInstance.config.timeout,
    method: "get",
    baseURL: apiInstance.config.baseURL,
    url: url, // 请求地址
    responseType: "blob", // 表明返回服务器返回的数据类型
    headers: { token: localStorage.getItem("token") },
  })
    .then((res) => {
      if (!res.data) {
        message.error(res.data.message!);
        return false;
      }
      const disposition = res.headers["content-disposition"];
      let fileName: any = disposition?.substring(
        disposition.indexOf("filename=") + 9,
        disposition.length
      );
      var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
      var isOpera = userAgent.indexOf("Opera") > -1;
      //判断是否IE浏览器
      if (
        userAgent.indexOf("compatible") > -1 &&
        userAgent.indexOf("MSIE") > -1 &&
        !isOpera
      ) {
        fileName = decodeUtf8(fileName);
      } else {
        fileName = decodeURI(fileName!);
        // 去掉双引号
        fileName = fileName.replace(/\"/g, "");
      }
      const str = fileName.split(".");
      
      function decodeUtf8(bytes) {
        var encoded = "";
        for (var i = 0; i < bytes.length; i++) {
          encoded += "%" + bytes[i].toString(16);
        }
        return decodeURIComponent(encoded);
      }
      if (typeof window.navigator.msSaveBlob !== "undefined") {
        window.navigator.msSaveBlob(
          new Blob([res.data], {
            type: "application/vnd.ms-excel",
          }),
          fileName
        );
      } else {
        let url = window.URL.createObjectURL(
          new Blob([res.data], {
            type: "application/vnd.ms-excel",
          })
        );
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); //下载完成移除元素
        window.URL.revokeObjectURL(url); //释放掉blob对象
      }
    })
    .catch((err) => {
      console.log(err);
      message.error(err.data?.message!);
    });
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值