vue实现导入Excel数据

导入

1、api链接

 introductionCarModelInfoApi='/carModel/info/introductionCarModelInfo',

2、接口操作

export function importExcel(data: any) {
  return new Promise(async () => {
    const { createMessage ,createConfirm} = useMessage();
    const formData = new FormData();//转换fromData格式
    formData.append('file', data);//传给后端的参数,
    defHttp
      .request(
        {
          url: `/af-zk-carmodel${Api.introductionCarModelInfoApi}`,
          method: 'post',
          params: formData,
        },
        {
          isTransformRequestResult: false,//框架配置 用于页面代码可能需要直接获取code,data,message这些信息时开启
          apiUrl: import.meta.env.DEV ? '/basic-api/af' : '',
        }
      )
      .then((res) => {
        if (res.data.code=== '000000') {
          // createMessage.success('数据传输完成,请稍后重新查询列表数据');
          createConfirm({
            iconType: 'success',
            content: `成功${res.data.data.successNum}条,失败${res.data.data.defaltNum}条`,
          });
        } else {
          createMessage.error('导入失败,请稍后再试');
        }
      });
  });
}

3、自己封装的上传方法,引入到使用的页面直接调用标签

<template>
  <div style="display: inline">
    <input
      ref="inputRef"
      type="file"
      v-show="false"
      accept=".xlsx, .xls"
      @change="handleInputClick"
    />
    <div @click="handleUpload" style="display: inline">
      <slot></slot>
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';

  export default defineComponent({
    name: 'ImportExcel',
    emits: ['success', 'error'],
    setup(_, { emit }) {
      const inputRef = ref<HTMLInputElement | null>(null);
      const loadingRef = ref<Boolean>(false);

      /**
       * @description:  把excel数据转换成formData
       */
      function readerData(rawFile: File) {
        loadingRef.value = true;
        return new Promise((resolve, reject) => {
          let formData = new FormData();
          formData.append('file', rawFile);
          try {
            emit('success', formData);
            resolve('');
          } catch (error) {
            reject(error);
            emit('error');
          } finally {
            loadingRef.value = false;
          }
        });
      }

      async function upload(rawFile: File) {
        const inputRefDom = unref(inputRef);
        if (inputRefDom) {
          // fix can't select the same excel
          inputRefDom.value = '';
        }
        await readerData(rawFile);
      }

      /**
       * @description: 触发选择文件管理器
       */
      function handleInputClick(e: Event) {
        const files = e && (e.target as HTMLInputElement).files;
        const rawFile = files && files[0]; // only setting files[0]
        if (!rawFile) return;
        upload(rawFile);
      }

      /**
       * @description: 点击上传按钮
       */
      function handleUpload() {
        const inputRefDom = unref(inputRef);
        inputRefDom && inputRefDom.click();
      }

      return { handleUpload, handleInputClick, inputRef };
    },
  });
</script>

4、在当前文件的ts中重命名

import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';

export const ZkImpExcel = createAsyncComponent(() => import('./src/ZkImportExcel.vue'));
export * from './src/types';

export { jsonToSheetXlsx, aoaToSheetXlsx } from './src/Export2Excel';

6、在vue页面调用ZkImpExcel:为ts中const的名称

 <ZkImpExcel @success="loadDataSuccess">
          <a-button type="primary">导入</a-button>
        </ZkImpExcel>
        
 //  js导入
    function loadDataSuccess(excelData) {
      if (excelData.get('file')) {
        importExcel(excelData.get('file'));
      }
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值