vue实现excel表格复制粘贴

1、效果图

_20230727143704.png
_20230727143737.png
20230727144318.png

2、原理

因为现在的谷歌等浏览器从安全等角度考虑,禁止直接读取剪切板上的东西。所以要手动的实现粘贴的这一步,通过粘贴到text文档上,然后,使用for遍历,根据 \n 把每一行分开,然后再根据\t 把每一列的数据都提取出来,对应着存入到表格中。

3、具体代码

template

<el-table border :data="formTab.buyList" @paste.native="pasteInfo($event)" @cell-click="showDetail" cell-class-name="tableCellClassName" > </el-table>

data

      rowsInfo:[],
      emptyObj: {//只粘两个字段(即只粘贴两列)bir列开始粘贴,bir是第二列
        minQuantity:undefined,
        maxQuantity:undefined,
        fixedQuantity:undefined,
        materialPrice:undefined,
      },
      currentRowIndex:undefined,
      currentColumnIndex:undefined,
      currentColumnKey:undefined

methods

    tableCellClassName({row, column, rowIndex, columnIndex}) {
      //注意这里是解构
      //利用单元格的 className 的回调方法,给行列索引赋值
      column.index = columnIndex;
    },
    pasteInfo(e){
      try {
        e.preventDefault()
        var data = null;
        var clipboardData = e.clipboardData; // IE
        if (!clipboardData) {
          //chrome
          clipboardData = e.originalEvent.clipboardData;
        }
        data = clipboardData.getData("Text");
        //首先对源头进行解析
        var rowStrArray = data.split("\n");//拆成很多行
        this.rowsInfo = [];
        for (var i = 0; i < rowStrArray.length-1; i++) {
          var row = [];
          var tdStrArray = rowStrArray[i].split("\t");//按列拆分
          for (var j = 0; j < tdStrArray.length; j++) {
            row.push(tdStrArray[j]);
          }
          this.rowsInfo.push(row);
        }
        var reg=new RegExp("\r","g")
        for (var j = 0; j < this.rowsInfo.length; j++) {
          if(this.currentRowIndex+j > this.formTab.buyList.length - 1){
            break
          }
          this.temp = JSON.parse(JSON.stringify(this.formTab.buyList[this.currentRowIndex+j]))
          let num = 0
          let numFlag = 5//从哪一列开始粘贴:全部列都可以粘贴(即从第0列可以粘贴)
          for (var key in this.emptyObj) {
            if (this.currentColumnIndex+1 <= numFlag) {
              if (num<this.rowsInfo[j].length){
                this.temp[key] = this.rowsInfo[j][num].replace(reg,"");
                num = num + 1
              }
            }
            numFlag = numFlag + 1
          }
          this.$set(this.formTab.buyList, this.currentRowIndex+j, this.temp)
        }
      } catch(err) {
        this.$modal.msgError('请选择复制位置')
      }
    },
    showDetail(row, column, data, event){
      console.log(row, column,data, event)
      this.currentRowIndex = row.index
      this.currentColumnIndex = column.index
      this.currentColumnKey = column.property
    },
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容