vue+原生js实现从excel复制内容粘贴至table中展示

本文介绍如何在Vue项目中,利用原生JavaScript处理从Excel复制的内容,并将其粘贴到表格中展示。关键在于监听paste事件,阻止默认行为,通过分隔符拆分字符串,并将数据绑定到表格的input框。文章提供了完整的Vue代码示例,包括针对Element UI的优化处理。

 我收到的需求是查询条件以表格的形式展示,同时要支持从excel粘贴

该文件为vue文件,基本静态部分如下

<template>
  <div>
    <table style="margin-bottom: 20px">
      <tr>
        <td>GlassId</td>
        <td>X坐标</td>
        <td>Y坐标</td>
      </tr>
      <tr v-for="(item, index) in searchList" :key="index">
        <td>
          <input type="text" title="glassId" v-model="item.glassId" />
        </td>
        <td>
          <input type="text" title="X坐标" v-model="item.x" />
        </td>
        <td>
          <input type="text" title="Y坐标" v-model="item.y" />
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
const searchList = [];
for (let i = 0; i < 10; i++) {
  searchList.push({ glassId: "", x: "", y: "" });
}

export default {
  data() {
    return {
      searchList
    };
  }
};
</script>

<style scoped>
table,
td {
  border: 1px solid #333;
  border-collapse: collapse;
}
td {
  width: 200px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
td > input {
  width: 100%;
  height: 100%;
  border: 0;
  padding: 0 10px;
}
</style>

首先建立一个静态的table表格,每个td下都填满一个input框,方便v-model双向绑定数据(原本是用的div并给定可编辑的属性,后来发现和数据绑定比较麻烦,后决定用input)

 该需求主要的技术点在于js里的粘贴事件 paste,代码如下

document.addEventListener("paste", e => {
    e.preventDefault(); //阻止默认粘贴事件
    e.stopPropagation(); //阻止事件冒泡

    let paste = (e.clipboardData || window.clipboardData).getData("text"); //以text方式接收粘贴内容
    ...
})

声明粘贴事件后,首先要阻止默认的粘贴事件,不让内容粘贴到表格中 ,然后接收粘贴出来的数据

以上为excel原数据和控制台打印的paste,每各单元格之间由 \t 间隔开,行与行之间由 \r\n 间隔开,由于控制台的缘故,字符串的这些未作显示。

然后对接收到的paste字符串做处理,先按行分隔成数组

document.addEventListener("paste", e => {
    e.preventDefault(); //阻止默认粘贴事件
    e.stopPropagation(); //阻止事件冒泡

    let paste = (e.clipboardData || window.clipboardData).getData("text"); //以text方式接收粘贴内容

    let arr = paste.split("\r\n");
    console.log("arr:",arr);
    ...
})

拆分后的数组如下

 此时便可看到每行中的每个单元格都是由 \t 间隔开,接着我们再将数组里的每个字符串通过 \t 拆分成第二个维度的数组

document.addEventListener("paste", e => {
    e.preventDefault(); //阻止默认粘贴事件
    e.stopPropagation(); //阻止事件冒泡

    let paste = (e.clipboardData || window.clipboardData).getData("text"); //以text方式接收粘贴内容

    let arr = paste.split("\r\n");

    let list = arr
       .map(item => {
          return item.split("\t").filter(con => con);
        })
        .filter(item => item.length);
    console.log("list:",list);
})

两个 filter 方法是为了过滤掉空字符串,从上面打印的 arr 可以看到,通过 \r\n 做拆分时最后会留有一个空字符串,再通过 \t 做拆分时,每行数据最后实际也会拆分出一个字符串,所以需要 filter 进行一下过滤,打印值如下

 到此,粘贴而来的数据已经拆分完成,剩下的就是将数据填充至表格中了

document.addEventListener("paste", e => {
    e.preventDefault(); //阻止默认粘贴事件
    e.stopPropagation(); //阻止事件冒泡

    let paste = (e.clipboardData || window.clipboardData).getData("text"); //以text方式接收粘贴内容

    let arr = paste.split("\r\n");

    let list = arr
       .map(item => {
          return item.split("\t").filter(con => con);
        })
        .filter(item => item.length);

    //----获取当前聚焦是第几行
    let trIndex = e.target.parentNode.parentNode.rowIndex;
    let searchList = [...this.searchList];
    if (e.target.title == "glassId") {
        //若聚焦当前行的第一个单元格,则从当前行的第一个单元格起开始填充数据
        list.forEach((item, index) => {
            searchList[index + trIndex - 1] = {};
            searchList[index + trIndex - 1].glassId = item[0];
            searchList[index + trIndex - 1].x = item[1];
            searchList[index + trIndex - 1].y = item[2];
        });
    } else if (e.target.title == "X坐标") {
    //若聚焦当前行的第二个单元格,则从当前行的第二个单元格起,每行只填充第二、三格的数据
        list.forEach((item, index) => {
            searchList[index + trIndex - 1] = {};
            searchList[index + trIndex - 1].glassId = "";
            searchList[index + trIndex - 1].x = item[0];
            searchList[index + trIndex - 1].y = item[1];
        });
    } else if (e.target.title == "Y坐标") {
    //若聚焦当前行的第三个单元格,则从当前行的第三个单元格起,每行只填充第三个单元格
        list.forEach((item, index) => {
            searchList[index + trIndex - 1] = {};
            searchList[index + trIndex - 1].glassId = "";
            searchList[index + trIndex - 1].x = "";
            searchList[index + trIndex - 1].y = item[0];
        });
    }
})

以上就是粘贴方法的全部内容,下面贴上整个vue代码

<template>
  <div>
    <table style="margin-bottom: 20px">
      <tr>
        <td>GlassId</td>
        <td>X坐标</td>
        <td>Y坐标</td>
      </tr>
      <tr v-for="(item, index) in searchList" :key="index">
        <td>
          <input type="text" title="glassId" v-model="item.glassId" />
        </td>
        <td>
          <input type="text" title="X坐标" v-model="item.x" />
        </td>
        <td>
          <input type="text" title="Y坐标" v-model="item.y" />
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
const searchList = [];
for (let i = 0; i < 10; i++) {
  searchList.push({ glassId: "", x: "", y: "" });
}

export default {
  data() {
    return {
      searchList
    };
  },
  mounted() {
    document.addEventListener("paste", e => {
      e.preventDefault(); //阻止默认粘贴事件
      e.stopPropagation(); //阻止事件冒泡

      let paste = (e.clipboardData || window.clipboardData).getData("text"); //以text方式接收粘贴内容
      //----将excel复制内容拆分成二维数组,第一维度为行数,第二维度为具体每行的数据
      let arr = paste.split("\r\n");
      let list = arr
        .map(item => {
          return item.split("\t").filter(con => con);
        })
        .filter(item => item.length);
      //----获取当前聚焦是第几行
      let trIndex = e.target.parentNode.parentNode.rowIndex;
      let searchList = [...this.searchList];
      if (e.target.title == "glassId") {
        //若聚焦当前行的第一个单元格,则从当前行的第一个单元格起开始填充数据
        list.forEach((item, index) => {
          searchList[index + trIndex - 1] = {};
          searchList[index + trIndex - 1].glassId = item[0];
          searchList[index + trIndex - 1].x = item[1];
          searchList[index + trIndex - 1].y = item[2];
        });
      } else if (e.target.title == "X坐标") {
        //若聚焦当前行的第二个单元格,则从当前行的第二个单元格起,每行只填充第二、三格的数据
        list.forEach((item, index) => {
          searchList[index + trIndex - 1] = {};
          searchList[index + trIndex - 1].glassId = "";
          searchList[index + trIndex - 1].x = item[0];
          searchList[index + trIndex - 1].y = item[1];
        });
      } else if (e.target.title == "Y坐标") {
        //若聚焦当前行的第三个单元格,则从当前行的第三个单元格起,每行只填充第三个单元格
        list.forEach((item, index) => {
          searchList[index + trIndex - 1] = {};
          searchList[index + trIndex - 1].glassId = "";
          searchList[index + trIndex - 1].x = "";
          searchList[index + trIndex - 1].y = item[0];
        });
      }
      this.searchList.splice(0, this.searchList.length, ...searchList);
    });
  }
};
</script>

<style scoped>
table,
td {
  border: 1px solid #333;
  border-collapse: collapse;
}
td {
  width: 200px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
td > input {
  width: 100%;
  height: 100%;
  border: 0;
  padding: 0 10px;
}
</style>

希望能帮助到你

--------------- 分割线(2023-04-20) ------------------

这两天才上来看了下,有两位提出element ui不生效,原因主要获取当前聚焦是第几行的时候产生的,所以又加了几段代码做完善

 上图修改了找寻tr的方法,下图增加了methods,定义一个公用寻找父元素的方法

一下贴上使用element ui的全部代码 

<template>
  <div>
    <table style="margin-bottom: 20px">
      <tr>
        <td>GlassId</td>
        <td>X坐标</td>
        <td>Y坐标</td>
      </tr>
      <tr v-for="(item, index) in searchList" :key="index" class="trItem">
        <td>
          <!-- <input type="text" title="glassId" v-model="item.glassId" /> -->
          <el-input v-model="item.glassId" title="glassId" />
        </td>
        <td>
          <!-- <input type="text" title="X坐标" v-model="item.x" /> -->
          <el-input v-model="item.x" title="X坐标" />
        </td>
        <td>
          <!-- <input type="text" title="Y坐标" v-model="item.y" / -->
          <el-input v-model="item.y" title="Y坐标" />
        </td>
      </tr>
    </table>
  </div>
</template>
 
<script>
const searchList = [];
for (let i = 0; i < 10; i++) {
  searchList.push({ glassId: "", x: "", y: "" });
}

export default {
  data() {
    return {
      searchList
    };
  },
  mounted() {
    document.addEventListener("paste", e => {
      e.preventDefault(); //阻止默认粘贴事件
      e.stopPropagation(); //阻止事件冒泡

      let paste = (e.clipboardData || window.clipboardData).getData("text"); //以text方式接收粘贴内容
      //----将excel复制内容拆分成二维数组,第一维度为行数,第二维度为具体每行的数据
      let arr = paste.split("\r\n");
      let list = arr
        .map(item => {
          return item.split("\t").filter(con => con);
        })
        .filter(item => item.length);
      //----获取当前聚焦是第几行
    //   let trIndex = e.target.parentNode.parentNode.rowIndex;
      let trIndex = this.findParent(e.target, "trItem").rowIndex;

      let searchList = [...this.searchList];
      if (e.target.title == "glassId") {
        //若聚焦当前行的第一个单元格,则从当前行的第一个单元格起开始填充数据
        list.forEach((item, index) => {
          searchList[index + trIndex - 1] = {};
          searchList[index + trIndex - 1].glassId = item[0];
          searchList[index + trIndex - 1].x = item[1];
          searchList[index + trIndex - 1].y = item[2];
        });
      } else if (e.target.title == "X坐标") {
        //若聚焦当前行的第二个单元格,则从当前行的第二个单元格起,每行只填充第二、三格的数据
        list.forEach((item, index) => {
          searchList[index + trIndex - 1] = {};
          searchList[index + trIndex - 1].glassId = "";
          searchList[index + trIndex - 1].x = item[0];
          searchList[index + trIndex - 1].y = item[1];
        });
      } else if (e.target.title == "Y坐标") {
        //若聚焦当前行的第三个单元格,则从当前行的第三个单元格起,每行只填充第三个单元格
        list.forEach((item, index) => {
          searchList[index + trIndex - 1] = {};
          searchList[index + trIndex - 1].glassId = "";
          searchList[index + trIndex - 1].x = "";
          searchList[index + trIndex - 1].y = item[0];
        });
      }
      this.searchList.splice(0, this.searchList.length, ...searchList);
    });
  },
  methods: {
    // 使用循环找到指定父节点
    findParent(target, className){
        // target为选中的起始节点,className为需要找到的父节点的class名
        let flag = true;
        let node = target;
        while(flag){
            node = node.parentNode;
            if(node.className.includes(className)){
                flag = false;
            }
        }
        return node;
    }
  }
};
</script>
 
<style scoped>
table,
td {
  border: 1px solid #333;
  border-collapse: collapse;
}
td {
  width: 200px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
td > input {
  width: 100%;
  height: 100%;
  border: 0;
  padding: 0 10px;
  outline: none;
  box-sizing: border-box;
}
</style>

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值