美文网首页
纯前端实现excel模板下载、上传到table表格

纯前端实现excel模板下载、上传到table表格

作者: 85d8c4f3886f | 来源:发表于2024-03-12 16:31 被阅读0次

需求介绍

点击“模板下载”按钮,下载excel模板,填写好数据之后点击“批量上传”按钮将数据push进下方的表格中,如果手机号与表格中的重复,或者是与excel其他行重复,这条数据不进行push操作,整体弹框提交时才会与后端进行交互。


image.png

相关技术栈、组件

vue3+antDesignVue(a-upload组件)+xlsx

具体实现

模板下载

 <a href="/static/模板.xlsx" download="模板">
      <a-button @click="" class="ml-10" v-if="showUpload">模板下载</a-button>
 </a>

这个功能很简单,需要注意的就是模板的位置需要放在\public\static\下面

image.png

批量下载

npm i xlsx
<a-upload
    v-if="showUpload"
    class="ml-10"
    v-model:file-list="fileList"
    name="file"
    action="/"
    @change="handleChange"
    :showUploadList="false"
 >
      <a-button> 批量上传 </a-button>
 </a-upload>
const handleChange = async (info) => {
      if (info.file.status != "error") return;
      const types = info.file.name.split(".")[1];
      const fileType = ["xlsx", "xls"].some((item) => item === types);
      if (!fileType) {
        proxy.$smallMsgFn("请上传正确的模板文件","error");
        return;
      }
      let dataBinary = await readFile(info.file);
      let workBook = xlsx.read(dataBinary, {
        type: "binary",
        cellDates: true,
      });
      let workSheet = workBook.Sheets[workBook.SheetNames[0]];
      const excelData = xlsx.utils.sheet_to_json(workSheet, { header: 1 });
      let arr = [];
      excelData.forEach((v, i) => {
        if (i == 0) return;
        if (v && v.length > 0) {
          let flag =
            !tabObj.tableData.some((i) => i.phone == v[3]) &&
            !arr.some((i) => i.phone == v[3]);
          if (flag) {
            arr.push({
              // rowId: v[0],
              userName: v[1],
              validate: v[2]?dayjs(v[2]).format("YYYY-MM-DD"):'',
              phone: v[3]?.toString(),
            });
          } else {
            proxy.$smallMsgFn("请上传正确格式的数据","error");
            return;
          }
        }
      });
      tabObj.tableData = [...tabObj.tableData, ...arr];
      tabObj.tableDataCopy = [...tabObj.tableDataCopy, ...arr];
    };
 const readFile = (file) => {
      return new Promise((resolve) => {
        let reader = new FileReader();
        reader.readAsBinaryString(file.originFileObj);
        reader.onload = (ev) => {
          resolve(ev.target?.result);
        };
      });
    };

有几个点需要注意下:

  • 1.if (info.file.status != "error") return;根据官方文档显示,上传的状态有很多种:uploading done error removed,写的时候发现uploading状态不是只出现一次,往表格push数据的时候会重复,所以用的error状态做判断,保证onchange里面的方法都只执行一次
  • 2.a-upload组件会将file外面再封装一层,所以file.originFileObj才是真正的源文件,不然的话reader.readAsBinaryString会报错Failed to execute ‘readAsBinaryString’ on ‘FileReader ‘: parameter 1 is not of type ‘Blob‘
    打印onchange的入参.png
  • 3.在往table中push的时候,需要注意数据的格式,比如我这里的手机号在excel中默认是Number类型,但接口请求的时候需要String格式。

大功告成!

相关文章

网友评论

      本文标题:纯前端实现excel模板下载、上传到table表格

      本文链接:https://www.haomeiwen.com/subject/myavzdtx.html