VUE xlsx.js 纯前端实现上传Excel文件,并读出来

功能

前端实现读取excel 判定限制上传表格最大行数

安装

npm install xlsx  --save

代码

 <el-upload class="upload"
               :show-file-list="false"
               :action="actionUrl"
               :on-change="importExcel"
               importExcel
               :on-preview="uploadRequestHandle"
               :auto-upload="false"
               :multiple="false"
               accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
               :limit="1">
      <el-button slot="trigger"
                 size="small"
                 type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;"
                 size="small"
                 type="success"
                 @click="submitUpload">上传到服务器</el-button>
    </el-upload>

methods:{
// 导入表格
    importExcel (param) {
      console.log(param);
      let _this = this;
      _this.file2Xce(param).then(item => {
        if (item && item.length > 0) {
          // xlsxJson就是解析出来的json数据,数据格式如下
          // [{sheetName: sheet1, sheet: sheetData }]
          if (item[0] && item[0].sheet && item[0].sheet.length) {
            // _this.tableData = item[0].sheet  //把数据塞到表格预览
            console.log(item[0].sheet, 'item[0].sheet');
            if (item[0].sheet.length > 10) {
              return this.$message.warning('导入的数据大于10条')
            }
          }
        }
      })
        .catch(error => {
          loading.close();
        });
    },
    /**
     * 解析文件
     * @param {Object} file
     */
    file2Xce (file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary"
          });
          const result = [];
          this.wb.SheetNames.forEach(sheetName => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            });
          });
          console.log(result) */
          resolve(result);
        };
        reader.readAsBinaryString(file.raw);
      });
    },
}

console.log(item[0].sheet, ‘item[0].sheet’);//这个就是表格的对象

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值