ant design分享记录-js-xlsx导入解析数据,并编辑

ant design vue上传excel文件,解析excel里的内容进行上传

 npm install xlsx
<a-upload
		:showUploadList="false"
        name="file"
        :beforeUpload="beforeUpload"
        @change="handleChange"
        :disabled="uploadLoad"
        >
          <a-button :loading="uploadLoad">
            <jihao-icon v-show="uploadLoad?false:true" title="导入模版"
                        type="icon_piliangdaoru"></jihao-icon>
            导入模版
          </a-button>
        </a-upload>
// 弹窗模版
<a-modal
        :width="1060"
        :centered="true"
        title="导入模版-确认"
        :visible="importVisible"
        :confirm-loading="confirmLoading"
        @ok="handleBatchImportData"
        @cancel="handleImportCancel(false)"
      >
        <a-table
          ref="table1"
          rowKey="categoryId"
          :columns="columns1"
          :dataSource="data"
          :pagination="false"
          bordered
        >
          <template
            v-for="col in ['categoryName', 'distribuName']"
            :slot="col"
            slot-scope="text, record, index">
            <div :key="col">
              <a-select
                v-if="col==='distribuName'"
                v-model="record.distribuId"
                placeholder="请选择设备分布地"
              >
                <a-select-option v-for="(item, index) in distribuList" :key="index" :value="item.distributionId">
                  {{ item.distributionName }}</a-select-option>
              </a-select>
              <a-select
                v-if="col==='categoryName'"
                v-model="record.categoryId"
                placeholder="请选择设备分类"
              >
                <a-select-option v-for="(item, index) in categoryList" :key="index" :value="item.categoryId">
                  {{ item.name }}</a-select-option>
              </a-select>
            </div>
          </template>
          <span slot="action" slot-scope="text, record, index">
          <template>
            <a-button @click="handleTableDeleteRow(index)" style="padding: 0 6px;font-size: 12px;height: 26px;">
              <jihao-icon style="font-size: 13px;" title="删除" type="icon_delete_device"></jihao-icon>
              <span style="font-size: 12px;">删除</span>
            </a-button>
          </template>
        </span>
        </a-table>
      </a-modal>
import XLSX from 'xlsx'
export default {
    name: 'DeviceIndex',
    components: {
      XLSX
    },
    data () {
      return {
      	uploadLoad:false,
      	importVisible:false,
      	confirmLoading:false,
      	data:[],
      	distribuList:[
      	{
      	distributionName:'深圳'
      	},{
      	distributionName:'上海'
      	}
		],
		categoryList:[
		{
		name:'分类1'
		},{
		name:'分类2'
		}
		]
      }
    },
   	methods: {
      beforeUpload(file) {
        let result = ''
        const fileArray = file.name.split(".")
        const suffix = fileArray[fileArray.length-1]
        if(!suffix){
          result = false
          return result
        }
        const xlslist = ['xls','xlsx']
        result = xlslist.some(function(item){
          return item === suffix
        })
        if(!result){
          return "请选择xls,或者xlsx文件导入!"
        }
        this.readExcel(file).then(tabJson => {
          if (tabJson && tabJson.length > 0) {
            this.data = tabJson[0].sheet
            this.importVisible = true
            console.log('数据', this.data)
          }
        })
        // 不进行上传操作
        return false
      },
      // 这个上传操作可以删掉
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.uploadLoad = true
          this.$message.success('文件上传中,请勿刷新或关闭页面');
          return
        }
        if (info.file.status === 'done') {
          this.uploadLoad = false
          if (info.file.response.code === 0) {
            this.$message.success(`${info.file.name} 文件上传成功!`);
          } else {
            this.$message.error(`${info.file.name}` + info.file.response.message)
          }
          //this.$refs.table.refresh()
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 文件上传失败!`);
          this.uploadLoad = false
        }
      },
      readExcel(file) {// 解析Excel
        let _this = this;
        return new Promise(function(resolve, reject){// 返回Promise对象
          const reader = new FileReader();
          reader.onload = (e) => {// 异步执行
            try {
              // 以二进制流方式读取得到整份excel表格对象
              let data = e.target.result,workbook = XLSX.read(data, {type: 'binary'});
              // let batteryArr = [];
              const result = [];
              for (let item in workbook.SheetNames){
                let SheetName = workbook.SheetNames[item]
                let sheetInfos = workbook.Sheets[SheetName];
                let arr = []
                let outdata = XLSX.utils.sheet_to_json(sheetInfos);
                outdata.map(v => {
                  let obj = {}
                  obj.deviceSn = v.设备编号
                  obj.deviceName = v.设备名称
                  obj.categoryName = v.设备分类
                  obj.distribuName = v.设备分布地
                  obj.categoryId = v.设备分类ID
                  obj.distribuId = v.设备分布地ID
                  arr.push(obj)
                })
                result.push({
                  sheetName: SheetName,
                  sheet: arr
                });
              }
              resolve(result);
            } catch (e) {
              reject(e.message);
            }
          };
          reader.readAsBinaryString(file);
        });
      },
      handleImportCancel (visible) {
        if (!visible) {
          this.importVisible = false
        }
      },
      handleBatchImportData (){
		// 提交事件
      },
    }
 }

效果图
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值