切换模式
从Excel复制数据粘贴到el-table中
给div添加
contenteditable="true"
属性,使其可编辑监听div的paste事件,获取粘贴的数据
@paste.native="getCopy($event)"
将数据转换为json格式,并解析为表格数据
将表格数据赋值给el-table的data属性
vue
<template>
<div class="app-container" contenteditable="true" @paste.native="getCopy($event)">
<el-table :data="tableData">
<el-table-column label="id" prop="id" width="80"></el-table-column>
<el-table-column label="num1" prop="num1" width="80"></el-table-column>
<el-table-column label="num2" prop="num2" width="80"></el-table-column>
</el-table>
</div>
</template>
<script>
import { reactive, toRefs } from "vue"
export default {
name: "temp",
setup() {
const data = reactive({
title: "",
tableData: []
})
const getCopy = (event) => {
// 阻止默认粘贴行为
event.preventDefault()
// 获取粘贴的数据
const text = (event.originaEvent || event).clipboardData.getData("text/plain")
// 处理数据
const lines = text.split('\n')
const parsedData = lines.map(line => line.split('\t'))
// 去除可能的空行或空数组
let list = parsedData.filter(row => row.length > 0)
list.pop()
list.forEach(item => {
data.tableData.unshift({
id: item[0],
num1: item[1],
num2: item[2]
})
})
}
return {
...toRefs(data),
getCopy
}
}
};
</script>
<template>
<div class="app-container" contenteditable="true" @paste.native="getCopy($event)">
<el-table :data="tableData">
<el-table-column label="id" prop="id" width="80"></el-table-column>
<el-table-column label="num1" prop="num1" width="80"></el-table-column>
<el-table-column label="num2" prop="num2" width="80"></el-table-column>
</el-table>
</div>
</template>
<script>
import { reactive, toRefs } from "vue"
export default {
name: "temp",
setup() {
const data = reactive({
title: "",
tableData: []
})
const getCopy = (event) => {
// 阻止默认粘贴行为
event.preventDefault()
// 获取粘贴的数据
const text = (event.originaEvent || event).clipboardData.getData("text/plain")
// 处理数据
const lines = text.split('\n')
const parsedData = lines.map(line => line.split('\t'))
// 去除可能的空行或空数组
let list = parsedData.filter(row => row.length > 0)
list.pop()
list.forEach(item => {
data.tableData.unshift({
id: item[0],
num1: item[1],
num2: item[2]
})
})
}
return {
...toRefs(data),
getCopy
}
}
};
</script>