vue导入表格

vue导入表格

一、在untils文件里面封装一个common.js文件

import { utils as XLSXUtils, read as XLSXRead } from "xlsx";

function parseXlsx(file, fields) {
  return new Promise((resolve, reject) => {
    const name = file.name;
    const reader = new FileReader();
    reader.onload = function (e) {
      const data = e.target.result;
      const wb = XLSXRead(data, { type: "binary" });
      const listData = XLSXUtils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

      function findKey(obj, value, compare = (a, b) => a === b) {
        return Object.keys(obj).find((k) => compare(obj[k], value));
      }
      listData.forEach((item) => {
        for (let i in item) {
          const key = findKey(fields, i);
          if (fields.hasOwnProperty(key)) {
            item[key] = item[i];
          }
          delete item[i]; //删除原先的对象属性
        }
      });
      resolve(
        Object.assign([], listData).filter((item) => Object.keys(item).length)
      );
    };
    reader.readAsBinaryString(file);
  });
}

export default {
  parseXlsx,
};

二、在文件里面引入该js文件

<template>
<div @click="handleImportExcel">导入<div>
</template>

<script>
import until from "@/utils/common";
data() {
	return {
		list:[]//'
	}
}
computed: {
    fields() {
      return {
        plateNo: "托盘编号(必填)",
        chipcode: "芯片号",
        barcode: "条形码",
        shopId: "商户ID(必填)",
        shopName: "商户名称(必填)",
        status: "状态(启用/禁用)",
      };
    },
  },
 methods:{
	handleImportExcel(file) {
		const fildes = this.fields;

      const list = await until.parseXlsx(file, fildes);
      if (!list.length) {
        this.$message.error("检测到没有数据,请检测导入的文件!");
        return Promise.reject();
      }
      console.log(list, "list");
      this.fileName = file.name;
      this.list = list;//传给后端杰口饿数据
	}
}
</script>

你可能感兴趣的:(vue,vue.js,javascript,前端)