项目场景:
使用软件录入数据时一条条的输入太慢,在excel中整理数据,将excel中整理好的数据直接复制粘贴
到表格中(前提粘贴dom应该是可输入的才可粘贴),并在页面中添加清空
数据功能。
效果图如下(红框为粘贴的excel中的数据):
思路:
- 获取当前粘贴列和行的索引;获取所有列名称集合;
- 转化粘贴的内容;
- 最后将格式化的内容填到table中;
解决方法
代码如下:
<el-table border stripe :data="tableData" height="100%" ref="tableRef">
<el-table-column :resizable="false" width="60" type="index" label="序号"></el-table-column>
<el-table-column :resizable="false" label="企业名称" prop="CompanyName"></el-table-column>
<el-table-column :resizable="false" show-overflow-tooltip v-for="item in tableHead" :key="item" :label="item" :prop="item+''">
<template slot-scope="scope">
<div @click="cellClick(scope.$index,item)">
<el-input v-if="scope.$index === tabClickIndex && item === tabClickLabel" :ref="item" v-model="scope.row[item]" size="mini" @blur="inputBlur(scope.row,item,'setProjectConfig')" @paste.native="pasteMe($event,scope)" />
<span v-else> {{ scope.row[item]==null || scope.row[item]=='' ?0 : scope.row[item] }}</span>
</div>
</template>
</el-table-column>
</el-table>
pasteMe(e, scope) {
e.preventDefault() //阻止默认粘贴事件
e.stopPropagation() //阻止事件冒泡
// 是取得当前dom的table的列和数据,td,tr的索引
let tableNode = ''
let trIndex = scope.$index
let colIndex = ''
let tableParentObj = e.target.parentNode
for (var i = 0; i < 100; i++) {
// includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。
if (tableParentObj.className.includes('el-table el-table--fit el-table--striped')) {
tableNode = tableParentObj.__vue__
break
}
tableParentObj = tableParentObj.parentNode
}
let tableColumns = tableNode.columns //表格所有列集合
let tableData = tableNode.data //表格数据
let columnName = [] //列所有名称的集合
if (tableColumns.length > 0) {
tableColumns.map((item) => {
columnName.push(item.property)
})
}
colIndex = columnName.findIndex((x) => x == scope.column.property)
//----获取当前聚焦数据
let pasteData = (e.clipboardData || window.clipboardData).getData('text') //以text方式接收粘贴内容
//----将excel复制内容拆分成二维数组,第一维度为行数,第二维度为具体每行的数据
let arr = pasteData.split('\r\n')
// 如果某一行是空的删除
if (!arr[arr.length - 1].length) {
arr.splice(arr.length - 1, 1)
}
let list = arr //拿到数据源
.map((item) => {
return item.split('\t')
})
.filter((item) => item.length)
let afterColumnName = [] //根据粘贴的数据判断出需要填充数据的列名称
if (columnName.length > 0) {
columnName.map((item, index) => {
if (index >= colIndex) {
if (afterColumnName.length >= list[0].length) {
return
}
afterColumnName.push(item)
}
})
}
let num = 0
if (tableData.length > 0) {
tableData.map((item, index) => {
if (index >= trIndex) {
if (num >= list.length) {
return
}
if (afterColumnName.length > 0) {
afterColumnName.map((col, colindex) => {
if (col.length > 0) {
tableData[index][col] = list[num][colindex]
}
})
num++
}
}
})
}
}
清空功能的代码如下:
// 清空
clear() {
this.tableData.forEach((item) => {
// 清空基础表格数据
this.yearList.forEach((year) => {
item[year] = 0
})
})
},