封装拥有excel的table
发表于:2025-08-05 |

前言

因为老板看到了别人家的批量编辑可以做到这个效果,就想要我们系统也加这个功能,我知道网上已经有很多现成的这种带类似 excel 功能的 table 了,但是吧,我这里的代码已经有点屎山了,里面逻辑啥的都很复杂,自然不可能全部推倒,将基础的 table 组件换成他们的,因此,我就自己研究了一下这个功能。本文基于 vue3+tdesign 的 table 进行实现,你可以把 table 换车你自己的 table,核心就是我封装的那些个方法。内容有点多,也有点乱,如果你有这样的需求的话,可以借鉴参考一下。

功能需求

  1. 点击单元格高亮行列
  2. 点击单元格进行输入
  3. 点击选中单元格,具有边框,和右下方小点
  4. 鼠标按下,可以拖选多个单元格
  5. 框选内容进行复制和 Backspace 直接删
  6. 支持粘贴 excel 格式内容进入单元格
  7. 点击小点,进行单元格内容复制
  8. 点击表头选中列,点击序号选中行
  9. 方向键,tab,回车键调整选中单元格

绘制普通的 table 组件

因为业务需求,我不可能分享我公司的业务代码给大家,我给的都是很简单的案例,大家能理解如何实现即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<template>
<div class="excel-table">
<t-table
:columns="columns"
:data="tableData"
max-height="95vh"
bordered
></t-table>
</div>
</template>
<script setup>
import { onMounted, ref } from "vue";
// table列
const columns = ref([]);

// table数据
const tableData = ref([]);

// 初始化列
const initColumns = () => {
const arr = [{ colKey: "serial-number", title: "序号", width: 80 }];
for (let i = 65; i <= 90; i++) {
const key = String.fromCharCode(i);
arr.push({
title: key,
colKey: key + "colKey",
width: 100,
});
}
columns.value = arr;
};

// 初始化table数据
const initTableData = () => {
const arr = [];
for (let i = 0; i <= 50; i++) {
const eachData = {};
for (let j = 65; j <= 90; j++) {
const key = String.fromCharCode(j);
eachData[key + "colKey"] = "";
}
arr.push(eachData);
}
tableData.value = arr;
};

onMounted(() => {
initTableData();
initColumns();
});
</script>
<style scoped>
.excel-table {
margin: 0;
padding: 0;
background: #f5f5f5;
}
</style>

这里我先绘制了一个很简单的 table 组件,样式啥的我就先不管了,暂时先这样。我主要讲解逻辑,此时效果如下
效果图

完成需求

需求 1:点击单元格高亮行列

首先,我们要明确,我们这是一个可封装的模块,因此可以单独写一个 hook 出去。

初始化新建一个 hook

新建一个 hook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { reactive } from "vue";

export function useExcelSelection() {
// 处理点击行高亮
const curNeedHighLightRowAndCol = reactive({
row: -1,
col: -1,
});

const handleHighlight = (rowIndex: number, colIndex: number) => {
curNeedHighLightRowAndCol.row = rowIndex;
curNeedHighLightRowAndCol.col = colIndex;
};

return {
curNeedHighLightRowAndCol,
handleHighlight,
};
}

导入使用

然后在使用的地方导入

1
2
3
import { useExcelSelection } from "@/hooks/useExcelSelection";
const excelSelection = useExcelSelection();
const { curNeedHighLightRowAndCol, handleHighlight } = excelSelection;

处理点击单元格逻辑

1
2
3
4
const handleCellClick = (param) => {
const { colIndex, rowIndex } = param;
handleHighlight(rowIndex, colIndex);
};

这里我用了 tdesign 的列插槽渲染列,给列加上了点击事件,绑定了动态 class 获取高亮,其实如果是 tdesign 我完全可以使用 className 和 cellClick 来实现的,这样写只是为了方便大家理解,其实就是点击单元格处理事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div class="excel-table">
<t-table
:columns="columns"
row-key="id"
:data="tableData"
max-height="95vh"
bordered
>
<!-- 插槽自定义渲染单元格 -->
<template
v-for="item in tableColKeys"
:key="item"
#[item]="{ row, col, rowIndex, colIndex }"
>
<div :class="getCellHighlightColorClass(rowIndex, colIndex)">
<div
class="no-edit-cell"
@click="handleCellClick({ rowIndex, colIndex })"
>
{{ row[col.colKey] }}
</div>
</div>
</template>
</t-table>
</div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// table的colKey
const tableColKeys = computed(() => {
return columns.value.map((item) => item.colKey);
});

// 获取class样式
const getCellHighlightColorClass = (rowIndex, colIndex) => {
// 总的颜色类
let classArr = [];
/**
* 处理非excel的,自己的逻辑,加上颜色类
*/
// excel颜色类
const excelColor = getHighlightColorClass(rowIndex, colIndex);
// 拼接excel颜色类
classArr = classArr.concat(excelColor);
const str = classArr.join(" ");
return str;
};

然后在 hook 中加上getCellHighlightColorClass逻辑

1
2
3
4
5
6
7
const getHighlightColorClass = (rowIndex: number, colIndex: number) => {
const { row, col } = curNeedHighLightRowAndCol;
const validate1 = row === rowIndex || col === colIndex;
const classArr = [];
validate1 && classArr.push("highlight-row-col");
return classArr;
};

然后定义一下样式即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<style>
body {
--batchHighlightColor: #e6f1ff;
}
.excel-table {
.t-table th,
.t-table td {
padding: 0;
}
}
</style>
<style scoped lang="less">
.excel-table {
margin: 0;
padding: 0;
background: #f5f5f5;
}

.excel-table {
.highlight-row-col {
background-color: var(--batchHighlightColor) !important;
.t-input,
.t-input__inner {
background-color: var(--batchHighlightColor) !important;
}
}
}

.no-edit-cell {
height: 32px;
line-height: 32px;
padding: 0 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>

此时我们就完成了需求一,点击后效果如下
效果图

需求 2:点击单元格可以进行录入

这里我就展示个简单的了,就是点击变成 input 框,你可以根据你自己的需求把东西改成其他组件。

1
2
3
4
5
6
7
8
9
10
<div v-if="isEditing(rowIndex, colIndex)">
<t-input v-model="row[col.colKey]" placeholder=""></t-input>
</div>
<div
v-else
class="no-edit-cell"
@click="handleCellClick({ rowIndex, colIndex })"
>
{{ row[col.colKey] }}
</div>
1
2
3
4
5
6
7
// 是否在编辑状态
const isEditing = (rowIndex, colIndex) => {
const { row, col } = curNeedHighLightRowAndCol;
const validate1 = row === rowIndex && col === colIndex;
// 这里可以加上你需要的逻辑等
return Boolean(validate1);
};

也许你会问,为什么不直接把所有单元格变成 input,这是因为当我们的 tableData 数据比较大的时候,由于绑定了 v-model,单元格会全量更新,导致录入卡顿,当然你可以使用:value 和@change 的方式改造,这里我就写成这样了。

自动聚焦

然后为了避免我们点击第一次变成 input 之后,没有直接聚焦,我们加一个自动聚焦以及选中内容的逻辑。

首先给 input 加个 id

这里你也可以加上动态 ref 进行,我这里为了方便,就使用了 id

1
2
3
4
5
6
7
<div v-if="isEditing(rowIndex, colIndex)">
<t-input
v-model="row[item]"
placeholder=""
:id="`batchTableInput${rowIndex}-${colIndex}`"
></t-input>
</div>
然后在点击的后面加上触发 focus 事件
1
2
3
4
5
6
7
8
9
10
11
12
13
// 点击单元格
const handleCellClick = (param) => {
const { colIndex, rowIndex } = param;
handleHighlight(rowIndex, colIndex);
nextTick(() => {
const id = `#batchTableInput${rowIndex}-${colIndex}`;
const parentDom = document.querySelector(id);
if (parentDom) {
const inputDom = parentDom.querySelector(".t-input__inner");
inputDom.focus();
}
});
};

当然,你可以把这个封装到 hook 里面,我这里传了个 key 进去作为标识,如果不带上 key 的话,多个这样的 table 存在就会出现 dom 获取错乱的情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { reactive, nextTick } from "vue";

export function useExcelSelection(param: { key: string }) {
const { key } = param;

// 处理点击行高亮
const curNeedHighLightRowAndCol = reactive({
row: -1,
col: -1,
});

const handleHighlight = (rowIndex: number, colIndex: number) => {
curNeedHighLightRowAndCol.row = rowIndex;
curNeedHighLightRowAndCol.col = colIndex;
};

const getHighlightColorClass = (rowIndex: number, colIndex: number) => {
const { row, col } = curNeedHighLightRowAndCol;
const validate1 = row === rowIndex || col === colIndex;
const classArr = [];
validate1 && classArr.push("highlight-row-col");
return classArr;
};

// 点击自动聚焦
const handleClickCellToFocus = (rowIndex: number, colIndex: number) => {
nextTick(() => {
const id = `#${key}${rowIndex}-${colIndex}`;
const parentDom = document.querySelector(id);
if (parentDom) {
const inputDom = parentDom.querySelector(
".t-input__inner"
) as HTMLElement;
inputDom.focus();
}
});
};

return {
curNeedHighLightRowAndCol,
handleHighlight,
getHighlightColorClass,
handleClickCellToFocus,
};
}

然后在使用的地方进行修改,大概如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const ELEMENT_KEY = "batchTableInput";

const excelSelection = useExcelSelection({
key: ELEMENT_KEY,
});
const {
curNeedHighLightRowAndCol,
handleHighlight,
getHighlightColorClass,
handleClickCellToFocus,
} = excelSelection;

// 点击单元格
const handleCellClick = (param) => {
const { colIndex, rowIndex } = param;
handleHighlight(rowIndex, colIndex);
handleClickCellToFocus(rowIndex, colIndex);
};

聚焦后全选单元格内容

加上选中内容的代码inputDom.setSelectionRange(0, String(inputDom.value).length);

1
2
3
4
5
6
7
8
9
10
11
12
// 点击自动聚焦
const handleClickCellToFocus = (rowIndex: number, colIndex: number) => {
nextTick(() => {
const id = `#${key}${rowIndex}-${colIndex}`;
const parentDom = document.querySelector(id);
if (parentDom) {
const inputDom = parentDom.querySelector(".t-input__inner") as HTMLInputElement;
inputDom.focus();
inputDom.setSelectionRange(0, String(inputDom.value).length);
}
});
}

此时我们点击单元格就会是这样的效果了
效果图

需求 3:点击选中单元格,具有边框,和右下方小点

添加单个的操作点

在 hook 中

这里我们先处理最简单的逻辑,就是点击添加边框逻辑,在 hook 中加上这段代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 添加操作点
const addOperatePoint = () => {
nextTick(() => {
const operatePoint = document.createElement("div");
operatePoint.className = `${key}operate-point`;
operatePoint.style.position = "absolute";
operatePoint.style.bottom = "-2.5px";
operatePoint.style.right = "-2.5px";
operatePoint.style.width = "8px";
operatePoint.style.height = "8px";
operatePoint.style.backgroundColor =
operatePointColor || "var(--td-brand-color-5)";
operatePoint.style.cursor = "crosshair";
operatePoint.style.zIndex = "100";
const cellDom = document.querySelector(`.highlight-end-cell`);
if (cellDom) {
cellDom.appendChild(operatePoint);
}
});
};

这里的样式其实都可以做成从 hook 传递的,我这里就处理一个颜色传递的给大家做个样子。

然后在获取样式中加上

1
2
3
4
5
6
7
8
9
10
// 获取高亮的样式
const getHighlightColorClass = (rowIndex: number, colIndex: number) => {
const { row, col } = curNeedHighLightRowAndCol;
const validate1 = row === rowIndex || col === colIndex;
const classArr = [];
validate1 && classArr.push("highlight-row-col");
const validate2 = row === rowIndex && col === colIndex;
validate2 && classArr.push("highlight-end-cell");
return classArr;
};

handleClickCellToFocus中调用addOperatePoint即可

在使用文件中
1
2
3
4
const excelSelection = useExcelSelection({
key: ELEMENT_KEY,
operatePointColor: "var(--td-success-color-5)",
});

然后要把单元格变成box-sizing:border-box,避免边框影响,因为我原先是32px的高度,现在上下都加了2pxborder,所以这里要改成28px

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.t-table--bordered td,
.t-table--bordered th {
box-sizing: border-box;
}
.highlight-end-cell {
box-sizing: border-box !important;
border: 2px solid var(--td-success-color-5) !important;
.t-input,
.t-input__inner {
height: 28px !important;
}
.no-edit-cell {
height: 28px !important;
line-height: 28px !important;
}
}

此时效果如下:
效果图

每次添加操作点前,去除之前的操作点

1
2
3
4
5
6
7
// 去除操作点
const clearOperatePoint = () => {
const operatePoint = document.querySelector(`.${key}operate-point`);
if (operatePoint) {
operatePoint.remove();
}
};

这样,我们就可以实现点击单元格,具有边框和右下方的小点了

需求 4:鼠标按下,可以拖选多个单元格

接下来,我们来实现,鼠标按下可以拖选多个单元格,然后鼠标松开之后,把这些单元格框起来,生成操作点。

设置 table 内容不可选中

因为我们拖拽,所以先要把内容设置不可选中

1
2
3
.t-table__content {
user-select: none;
}

监听鼠标按下,松开,经过事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<div
:class="getCellHighlightColorClass(rowIndex, colIndex)"
@mousedown.stop="
handleMouseDownMark({
rowIndex,
colIndex,
})
"
@mouseup.stop="
handleMouseUpMark({
rowIndex,
colIndex,
})
"
@mousemove.stop="
handleMouseMoveMark({
rowIndex,
colIndex,
})
"
>
...
</div>

然后我们去 hook 里面分别写这个方法即可

定义一些常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export interface MarkInfo {
rowIndex: number;
colIndex: number;
}

export interface CellParam {
rowIndex: number;
colIndex: number;
}

export const MARK_INIT_INFO = {
rowIndex: -1,
colIndex: -1,
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 开始的标记
const startMarkInfo = ref<MarkInfo>({
...MARK_INIT_INFO,
});

// 拖拽选区经过的cell
const moveRowColIndeKeyArr = ref<string[]>([]);

// 结束的标记
const endMarkInfo = ref<MarkInfo>({
...MARK_INIT_INFO,
});

// 是否在拖拽选区
const isDragging = ref(false);

handleMouseDownMark

这里的逻辑很简单,就是鼠标按下,重置那些参数,然后设置起点,设置isDragging

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 清除选区标记
const clearStartAndEndMark = () => {
startMarkInfo.value = {
...MARK_INIT_INFO,
};
endMarkInfo.value = {
...MARK_INIT_INFO,
};
moveRowColIndeKeyArr.value = [];
isDragging.value = false;
clearOperatePoint();
};

// 鼠标按下标记
const handleMouseDownMark = (param: CellParam) => {
clearStartAndEndMark();
const { rowIndex, colIndex } = param;
startMarkInfo.value = {
rowIndex,
colIndex,
};
isDragging.value = true;
};

handleMouseMoveMark

这里就是需要将经过的点全部pushmoveRowColIndeKeyArr,这里有一定的算法逻辑,简单来说就是根据起始点和最终点画一个框的逻辑,就是根据起始和结束点,把rowIndexcolIndex俩个区间内的所有单元格的点位给加进去

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 鼠标移动到cell上,计算经过的cell
const handleMouseMoveMark = (param: CellParam) => {
if (!isDragging.value) return;
const { rowIndex, colIndex } = param;
moveRowColIndeKeyArr.value = [];
// 从起点开始算,经过的cell
const startRowIndex = startMarkInfo.value.rowIndex;
const startColIndex = startMarkInfo.value.colIndex;
const endRowIndex = rowIndex;
const endColIndex = colIndex;
// 判断需要添加的点,
if (isDragging.value) {
// 如果是终点的rowIndex大于起点的rowIndex,则需要添加向下的点
if (endRowIndex >= startRowIndex) {
// 向下
for (let i = startRowIndex; i <= endRowIndex; i++) {
// 判断是向左还是向右
if (endColIndex > startColIndex) {
// 向右
for (let j = startColIndex; j <= endColIndex; j++) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
} else {
// 向左
for (let j = startColIndex; j >= endColIndex; j--) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
}
}
} else if (endRowIndex < startRowIndex) {
// 向上
for (let i = startRowIndex; i >= endRowIndex; i--) {
// 判断是向左还是向右
if (endColIndex > startColIndex) {
// 向右
for (let j = startColIndex; j <= endColIndex; j++) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
} else {
// 向左
for (let j = startColIndex; j >= endColIndex; j--) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
}
}
}
}
};

handleMouseUpMark

最后鼠标抬起的时候就直接加操作点即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 鼠标抬起标记
const handleMouseUpMark = (param: CellParam) => {
const { rowIndex, colIndex } = param;
if (isEmpty(moveRowColIndeKeyArr.value)) {
moveRowColIndeKeyArr.value = [`${rowIndex}-${colIndex}`];
}
if (!isDragging.value) {
addOperatePoint();
} else {
isDragging.value = false;
endMarkInfo.value = {
rowIndex,
colIndex,
};
addOperatePoint();
}
};

样式展示

这里你可以细节根据是否和起始点,结束点同行同列来进行不同的样式绘制,我这里的就简单点了

hook 中加上样式逻辑

前面的在handleClickCellToFocus点击单个点的那段逻辑可以去掉了,我们已经直接通过mouse事件加上了,这里我们调整一下获取样式的逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 获取样式
const getHighlightColorClass = (rowIndex: number, colIndex: number) => {
const { row, col } = curNeedHighLightRowAndCol;
// 是否高亮行列
const validate1 = row === rowIndex || col === colIndex;
const classArr = [];
// 是否是填充终点
const validate2 =
endMarkInfo.value?.rowIndex === rowIndex &&
endMarkInfo.value?.colIndex === colIndex;
// 是否是填充起点
const validate3 =
startMarkInfo.value?.rowIndex === rowIndex &&
startMarkInfo.value?.colIndex === colIndex;
// 是否是经过点
let validate4 = false;
if (!isEmpty(moveRowColIndeKeyArr.value)) {
const strRowColIndex = rowIndex + "-" + colIndex;
if (moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
validate4 = true;
}
}
// 高亮行列
validate1 && classArr.push("highlight-row-col");
// 结束点
validate2 && classArr.push("highlight-end-cell");
// 起始点
validate3 && classArr.push("highlight-start-cell");
// 经过点
validate4 && classArr.push("highlight-move-cell");
return classArr;
};

在使用的地方,定义样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.highlight-end-cell,
.highlight-move-cell,
.highlight-start-cell {
box-sizing: border-box !important;
border: 2px solid var(--td-success-color-5) !important;
.t-input,
.t-input__inner {
height: 28px !important;
}
.no-edit-cell {
height: 28px !important;
line-height: 28px !important;
}
}

此时效果如下:

需求 5:框选内容进行复制和 Backspace 直接删

我们现在已经有框选内容逻辑了,接下来加一个对这个框选内容进行复制和删除的逻辑

复制逻辑

这里我使用的是 vue3,所以安装了 vue3 复制的包,你可以根据你的实际情况安装一下,我这里使用的是vue-clipboard3

定义复制方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { NotifyPlugin } from "tdesign-vue-next";
import useClipboard from "vue-clipboard3";
// 复制
export const handleCopy = (param: {
text: string;
successMsg?: string;
errorMsg?: string;
}) => {
const { text, successMsg, errorMsg } = param;
const sourceText = text;
const successMessage = successMsg || "复制成功";
const errorMessage = errorMsg || "复制失败";
const { toClipboard } = useClipboard();
toClipboard(sourceText)
.then(() => {
NotifyPlugin.closeAll();
NotifyPlugin.success({
title: successMessage,
});
})
.catch(() => {
NotifyPlugin.closeAll();
NotifyPlugin.error({
title: errorMessage,
});
});
};
监听按键按下

hook 文件加上监听ctrl+c事件

1
2
3
4
5
6
7
8
9
10
// 处理键盘事件
const handleKeydown = async (e: KeyboardEvent) => {
// Ctrl+C / Cmd+C: 复制
if ((e.ctrlKey || e.metaKey) && e.key === "c") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length > 0) {
e.preventDefault();
copySelectionToClipboard();
}
}
};

使用文件中进行监听

1
2
3
4
5
6
7
8
9
10
onMounted(() => {
document
.querySelector(".excel-table")
.addEventListener("keydown", handleKeydown);
});
onBeforeUnmount(() => {
document
.querySelector(".excel-table")
.removeEventListener("keydown", handleKeydown);
});
处理复制方法

首先我们要把tableDatacolumns的数据给 hook

1
2
3
4
5
6
const excelSelection = useExcelSelection({
key: ELEMENT_KEY,
operatePointColor: "var(--td-success-color-5)",
getColumns: () => columns.value,
getTableData: () => tableData.value,
});

我们 hook 接受这俩方法后,可以通过这俩个方法来进行获取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 复制选区内容
const copySelectionToClipboard = () => {
const columns = getColumns();
const tableData = getTableData();
if (!moveRowColIndeKeyArr.value.length) return;
// 解析所有选中的 row/col
const cellList = moveRowColIndeKeyArr.value.map((str) => {
const [row, col] = str.split("-").map(Number);
return { row, col };
});
// 计算选区的最小/最大行列
const rows = cellList.map((c) => c.row);
const cols = cellList.map((c) => c.col);
const minRow = Math.min(...rows),
maxRow = Math.max(...rows);
const minCol = Math.min(...cols),
maxCol = Math.max(...cols);

// 构造二维数组
let result: string[][] = [];
for (let i = minRow; i <= maxRow; i++) {
let rowArr: string[] = [];
for (let j = minCol; j <= maxCol; j++) {
if (moveRowColIndeKeyArr.value.includes(`${i}-${j}`)) {
let colKey = columns[j].colKey;
rowArr.push(tableData[i][colKey]);
} else {
rowArr.push("");
}
}
result.push(rowArr);
}
// 转为 Excel 兼容的文本
const text = result.map((row) => row.join("\t")).join("\n");
if (text) {
handleCopy({
text: text.trim(),
});
} else {
NotifyPlugin.error({
title: "无内容复制",
});
}
};

上面这个方法也很好理解,就是获取最大最小的rowIndex,colIndex,进行text按照指定的顺序进行排版,然后将内容给复制方法。

通过剪贴板我们可以看到,内容是成功复制出来了
效果图

Backspace 逻辑

上面的复制逻辑知道了,那么 Backspace 逻辑也就很简单了,在 hook 事件监听中加入以下代码,为什么要moveRowColIndeKeyArr.value.length > 1呢?这是因为,一个单元格中,我们要允许光标切换删除文字指定内容,不能一棒子打死。然后我们允许父级传参onDeleteCell,把删除的逻辑交给父级,留足操作空间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Backspace: 删除
else if (e.key === "Backspace") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length > 1) {
e.preventDefault();
deleteSelection();
}
}

// 删除选区内容
const deleteSelection = () => {
if (!onDeleteCell) return;
const columns = getColumns();
moveRowColIndeKeyArr.value.forEach((item) => {
const [rowIndex, colIndex] = item.split("-").map(Number);
let colKey = columns[colIndex]?.colKey;
if (colKey) {
onDeleteCell(rowIndex, colKey);
}
});
};

这里显示我父级就不用触发其他逻辑了,就简单的删内容即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const excelSelection = useExcelSelection({
key: ELEMENT_KEY,
operatePointColor: "var(--td-success-color-5)",
getColumns: () => columns.value,
getTableData: () => tableData.value,
onDeleteCell: handleDeleteCell,
});

// 删除单元格回调
const handleDeleteCell = (rowIndex, colKey) => {
/**
* 处理你的清空内容逻辑
*/
tableData.value[rowIndex][colKey] = "";
};

此时,Backspace 就已经支持批量删除单元格内容了,同时保持了单个单元格内,删除部分文字的逻辑,大概效果如下

需求 6:支持粘贴 excel 格式内容进入单元格

定义方法

这里我们只需监听@paste="handlePaste"事件即可,我这里 table 进行了@paste="handlePaste"监听,然后你可以根据你的实际情况处理需要粘贴内容的格式,比如监听某个字符了,应该把数据进行转化成什么样子,我这里就啥也不做,就是普通的检测,这里的moveRowColIndeKeyArrpasteClipboardToSelection都是 hook 暴露出来的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 选区粘贴内容
function handlePasteCell(rowIndex, colKey, value) {
/**
* 处理你的复制赋值逻辑
*/
tableData.value[rowIndex][colKey] = value;
}

// 粘贴
function handlePaste(e) {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length >= 1) {
let text = e.clipboardData?.getData("text");
if (text) {
pasteClipboardToSelection(handlePasteCell, text);
e.preventDefault(); // 阻止默认粘贴行为
}
}
}

写 pasteClipboardToSelection 逻辑

这里也很简单,根据换行符进行判断,赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 粘贴选区内容
const pasteClipboardToSelection = async (
onPasteCell: (rowIndex: number, colKey: string, value: string) => void,
text: string
) => {
const columns = getColumns();
if (!moveRowColIndeKeyArr.value.length) return;
if (!text) return;
const rows = text.split(/\r?\n/).map((row) => row.split("\t"));
const cellList = moveRowColIndeKeyArr.value.map((str) => {
const [row, col] = str.split("-").map(Number);
return { row, col };
});
let flatValues: string[] = [];
for (let i = 0; i < rows.length; i++)
for (let j = 0; j < rows[i].length; j++) flatValues.push(rows[i][j]);
for (let i = 0; i < cellList.length; i++) {
const { row, col } = cellList[i];
let colKey = columns[col]?.colKey;
if (colKey) {
const value = flatValues[i] ?? "";
onPasteCell(row, colKey, value.trim());
}
}
};

此时效果如下:

需求 7:点击小点,进行单元格内容复制

接下来才是真核心,点击我们那个操作点,进行单元格的内容复制

给操作点加上监听事件

我们首先要在新增操作点的时候,给这个点加上对应的监听事件,这里加了三个事件,分别是dblclick,mousedown,mouseup

1
2
3
4
5
6
7
8
9
if (cellDom) {
cellDom.appendChild(operatePoint);
// 给这个点添加doubleclick事件
operatePoint.addEventListener("dblclick", handleOperatePointDblClick);
// 给这个点添加mouseup事件,避免直接触发handleMouseUpMark事件
operatePoint.addEventListener("mouseup", handleOperatePointMouseUp);
// 给这个点添加mousedown事件
operatePoint.addEventListener("mousedown", handleOperatePointMouseDown);
}

对应的,在移除点的时候,要移除方法的监听

1
2
3
4
5
6
7
8
9
10
// 去除操作点
const clearOperatePoint = () => {
const operatePoint = document.querySelector(`.${key}operate-point`);
if (operatePoint) {
operatePoint.addEventListener("mouseup", handleOperatePointMouseUp);
operatePoint.removeEventListener("mousedown", handleOperatePointMouseDown);
operatePoint.removeEventListener("dblclick", handleOperatePointDblClick);
operatePoint.remove();
}
};

handleOperatePointMouseDown

首先我们来写操作点按下事件,点击,记录操作点开启operatePointDragger

1
2
3
4
5
6
7
8
// 是否是根据操作点在拖拽
const operatePointDragger = ref(false);
// 操作点的mousedown事件处理函数
const handleOperatePointMouseDown = (e: Event) => {
e.preventDefault();
e.stopPropagation();
operatePointDragger.value = true;
};

操作点抬起

1
2
3
4
5
// 操作点抬起
const handleOperatePointMouseUp = (e: Event) => {
e.preventDefault();
e.stopPropagation();
};

鼠标抬起事件

修改鼠标抬起事件,这里定义了operatePointDragDirection拖拽方向,是横向的还是纵向的,mouseUpFunc是父级传给 hook 的,也是 hook 暴露出去的一个事件,这时候,就可以在父级进行判断逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 操作点拖拽方向
const operatePointDragDirection = ref<"horizontal" | "vertical" | null>(null);
// 鼠标抬起标记
const handleMouseUpMark = (param: CellParam) => {
const { rowIndex, colIndex } = param;
if (isEmpty(moveRowColIndeKeyArr.value)) {
moveRowColIndeKeyArr.value = [`${rowIndex}-${colIndex}`];
}
if (operatePointDragger.value) {
operatePointDragger.value = false;
}
if (!isDragging.value) {
addOperatePoint();
} else {
isDragging.value = false;
endMarkInfo.value = {
rowIndex,
colIndex,
};
addOperatePoint();
}
// 如果有移动点和框选点
if (
moveRowColIndeKeyArr.value.length > 0 &&
pointMoveRowColIndeKeyArr.value.length > 0
) {
nextTick(() => {
if (!operatePointDragDirection.value) {
operatePointDragDirection.value = "vertical";
}
mouseUpFunc && mouseUpFunc();
});
}
};

修改 handleMouseMoveMark

然后,我们需要修改handleMouseMoveMark方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// 拖拽选区经过的cell的最大行和列
const lastMaxMoveRowColIndeKeyArr = computed(() => {
// 根据moveRowColIndexKeyArr进行计算
const data = moveRowColIndeKeyArr.value;
let maxRowIndex = -1;
let maxColIndex = -1;
data.forEach((item) => {
const [rowIndex, colIndex] = item.split("-");
maxRowIndex = Math.max(maxRowIndex, Number(rowIndex));
maxColIndex = Math.max(maxColIndex, Number(colIndex));
});
return {
rowIndex: maxRowIndex,
colIndex: maxColIndex,
};
});

// 鼠标移动到cell上,计算经过的cell
const handleMouseMoveMark = (param: CellParam) => {
if (!isDragging.value && !operatePointDragger.value) return;
const { rowIndex, colIndex } = param;

// 得到最后一个经过的cell
// 如果是拖拽操作点,moveRowColIndeKeyArr.value不要重新设置
if (!operatePointDragger.value) {
moveRowColIndeKeyArr.value = [];
}
pointMoveRowColIndeKeyArr.value = [];

// 从起点开始算,经过的cell
const startRowIndex = startMarkInfo.value.rowIndex;
const startColIndex = startMarkInfo.value.colIndex;
const endRowIndex = rowIndex;
const endColIndex = colIndex;
// 判断需要添加的点,
if (isDragging.value) {
// 如果是终点的rowIndex大于起点的rowIndex,则需要添加向下的点
if (endRowIndex >= startRowIndex) {
// 向下
for (let i = startRowIndex; i <= endRowIndex; i++) {
// 判断是向左还是向右
if (endColIndex > startColIndex) {
// 向右
for (let j = startColIndex; j <= endColIndex; j++) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
} else {
// 向左
for (let j = startColIndex; j >= endColIndex; j--) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
}
}
} else if (endRowIndex < startRowIndex) {
// 向上
for (let i = startRowIndex; i >= endRowIndex; i--) {
// 判断是向左还是向右
if (endColIndex > startColIndex) {
// 向右
for (let j = startColIndex; j <= endColIndex; j++) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
} else {
// 向左
for (let j = startColIndex; j >= endColIndex; j--) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
}
}
}
}
// 进行拖拽复制
else if (operatePointDragger.value) {
// 获取操作点当前所在的位置(即选区结束位置)
const operatePointRowIndex = lastMaxMoveRowColIndeKeyArr.value.rowIndex;
const operatePointColIndex = lastMaxMoveRowColIndeKeyArr.value.colIndex;
const endRowIndex = rowIndex;
const endColIndex = colIndex;
// 判断方向,基于操作点位置和当前鼠标位置
const isHorizontal =
Math.abs(endColIndex - operatePointColIndex) >
Math.abs(endRowIndex - operatePointRowIndex);
// 设置操作点拖拽方向
operatePointDragDirection.value = isHorizontal ? "horizontal" : "vertical";

// 获取原始选区的范围
const originalData = moveRowColIndeKeyArr.value;

// 计算原始选区的行列范围
let originalRowIndices: number[] = [];
let originalColIndices: number[] = [];

originalData.forEach((item) => {
const [rowIndex, colIndex] = item.split("-");
originalRowIndices.push(Number(rowIndex));
originalColIndices.push(Number(colIndex));
});

originalRowIndices = [...new Set(originalRowIndices)].sort((a, b) => a - b);
originalColIndices = [...new Set(originalColIndices)].sort((a, b) => a - b);

// 横向复制
if (isHorizontal && !noHorizontalDrag) {
const isLeft = endColIndex < operatePointColIndex;
if (isLeft) {
// 向左复制:从操作点开始向左扩展,保持原始行数
const colDistance = operatePointColIndex - endColIndex + 1;
for (let colOffset = 0; colOffset < colDistance; colOffset++) {
const targetColIndex = operatePointColIndex - colOffset;
originalRowIndices.forEach((rowIndex) => {
const strRowColIndex = `${rowIndex}-${targetColIndex}`;
// 不在moveRowColIndeKeyArr.value中,才添加
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
} else {
// 向右复制:从操作点开始向右扩展,保持原始行数
const colDistance = endColIndex - operatePointColIndex + 1;
for (let colOffset = 0; colOffset < colDistance; colOffset++) {
const targetColIndex = operatePointColIndex + colOffset;
originalRowIndices.forEach((rowIndex) => {
const strRowColIndex = `${rowIndex}-${targetColIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
}
}
// 纵向复制
else if (!noVerticalDrag && !isHorizontal) {
const isUp = endRowIndex < operatePointRowIndex;
if (isUp) {
// 向上复制:从操作点开始向上扩展,保持原始列数
const rowDistance = operatePointRowIndex - endRowIndex + 1;
for (let rowOffset = 0; rowOffset < rowDistance; rowOffset++) {
const targetRowIndex = operatePointRowIndex - rowOffset;
originalColIndices.forEach((colIndex) => {
const strRowColIndex = `${targetRowIndex}-${colIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
} else {
// 向下复制:从操作点开始向下扩展,保持原始列数
const rowDistance = endRowIndex - operatePointRowIndex + 1;
for (let rowOffset = 0; rowOffset < rowDistance; rowOffset++) {
const targetRowIndex = operatePointRowIndex + rowOffset;
originalColIndices.forEach((colIndex) => {
const strRowColIndex = `${targetRowIndex}-${colIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
}
}
}
};

清除方法修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 清除选区标记
const clearStartAndEndMark = () => {
startMarkInfo.value = {
...MARK_INIT_INFO,
};
endMarkInfo.value = {
...MARK_INIT_INFO,
};
moveRowColIndeKeyArr.value = [];
pointMoveRowColIndeKeyArr.value = [];
isDragging.value = false;
operatePointDragger.value = false;
operatePointDragDirection.value = null;
clearOperatePoint();
};

修改样式

给操作点经过单元格添加样式,validate5逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 获取样式
const getHighlightColorClass = (rowIndex: number, colIndex: number) => {
const { row, col } = curNeedHighLightRowAndCol;
// 是否高亮行列
const validate1 = row === rowIndex || col === colIndex;
const classArr = [];
// 是否是填充终点
const validate2 =
endMarkInfo.value?.rowIndex === rowIndex &&
endMarkInfo.value?.colIndex === colIndex;
// 是否是填充起点
const validate3 =
startMarkInfo.value?.rowIndex === rowIndex &&
startMarkInfo.value?.colIndex === colIndex;
// 是否是选区经过点
let validate4 = false;
if (!isEmpty(moveRowColIndeKeyArr.value)) {
const strRowColIndex = rowIndex + "-" + colIndex;
if (moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
validate4 = true;
}
}
// 是否是操作点经过点
let validate5 = false;
if (!isEmpty(pointMoveRowColIndeKeyArr.value)) {
const strRowColIndex = rowIndex + "-" + colIndex;
if (pointMoveRowColIndeKeyArr.value.includes(strRowColIndex)) {
validate5 = true;
}
}
// 高亮行列
validate1 && classArr.push("highlight-row-col");
// 结束点
validate2 && classArr.push("highlight-end-cell");
// 起始点
validate3 && classArr.push("highlight-start-cell");
// 是否是选区经过点
validate4 && classArr.push("highlight-move-cell");
// 是否是操作点经过点
validate5 && classArr.push("highlight-point-move-cell");
return classArr;
};

父组件加上 css

然后添加highlight-point-move-cell的 css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.highlight-end-cell,
.highlight-move-cell,
.highlight-start-cell,
.highlight-point-move-cell {
box-sizing: border-box !important;
border: 2px solid var(--td-success-color-5) !important;
.t-input,
.t-input__inner {
height: 28px !important;
}
.no-edit-cell {
height: 28px !important;
line-height: 28px !important;
}
}
.highlight-point-move-cell {
border-color: var(--td-error-color) !important;
}

hook 代码

此时 hook 代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
import { reactive, nextTick, ref, computed } from "vue";
import { isEmpty } from "lodash";
import { NotifyPlugin } from "tdesign-vue-next";
import useClipboard from "vue-clipboard3";

export const MARK_INIT_INFO = {
rowIndex: -1,
colIndex: -1,
};

export interface MarkInfo {
rowIndex: number;
colIndex: number;
}

export interface CellParam {
rowIndex: number;
colIndex: number;
}

export const handleCopy = (param: {
text: string;
successMsg?: string;
errorMsg?: string;
}) => {
const { text, successMsg, errorMsg } = param;
const sourceText = text;
const successMessage = successMsg || "复制成功";
const errorMessage = errorMsg || "复制失败";
const { toClipboard } = useClipboard();
toClipboard(sourceText)
.then(() => {
NotifyPlugin.closeAll();
NotifyPlugin.success({
title: successMessage,
});
})
.catch(() => {
NotifyPlugin.closeAll();
NotifyPlugin.error({
title: errorMessage,
});
});
};

export function useExcelSelection(param: {
// 标识id
key: string;
// 不许横向拖拽操作点
noHorizontalDrag: boolean;
// 不许纵向拖拽操作点
noVerticalDrag: boolean;
// 鼠标抬起时回调
mouseUpFunc: any;
// 操作点颜色
operatePointColor: string;
// 表格列配置获取函数
getColumns: () => any[];
// 表格数据获取函数
getTableData: () => any[];
// 删除单元格回调
onDeleteCell?: (rowIndex: number, colKey: string) => void;
}) {
const {
key,
operatePointColor,
getColumns,
getTableData,
onDeleteCell,
noHorizontalDrag = false,
noVerticalDrag = false,
mouseUpFunc,
} = param;

// 开始的标记
const startMarkInfo = ref<MarkInfo>({
...MARK_INIT_INFO,
});

// 拖拽选区经过的cell
const moveRowColIndeKeyArr = ref<string[]>([]);

// 拖拽操作点经过的cell
const pointMoveRowColIndeKeyArr = ref<string[]>([]);

// 操作点拖拽方向
const operatePointDragDirection = ref<"horizontal" | "vertical" | null>(null);

// 结束的标记
const endMarkInfo = ref<MarkInfo>({
...MARK_INIT_INFO,
});

// 是否在拖拽选区
const isDragging = ref(false);

// 是否是根据操作点在拖拽
const operatePointDragger = ref(false);

// 当前高亮的点
const curNeedHighLightRowAndCol = reactive({
row: -1,
col: -1,
});

// 拖拽选区经过的cell的最大行和列
const lastMaxMoveRowColIndeKeyArr = computed(() => {
// 根据moveRowColIndexKeyArr进行计算
const data = moveRowColIndeKeyArr.value;
let maxRowIndex = -1;
let maxColIndex = -1;
data.forEach((item) => {
const [rowIndex, colIndex] = item.split("-");
maxRowIndex = Math.max(maxRowIndex, Number(rowIndex));
maxColIndex = Math.max(maxColIndex, Number(colIndex));
});
return {
rowIndex: maxRowIndex,
colIndex: maxColIndex,
};
});

// 点击处理高亮
const handleHighlight = (rowIndex: number, colIndex: number) => {
curNeedHighLightRowAndCol.row = rowIndex;
curNeedHighLightRowAndCol.col = colIndex;
};

// 获取样式
const getHighlightColorClass = (rowIndex: number, colIndex: number) => {
const { row, col } = curNeedHighLightRowAndCol;
// 是否高亮行列
const validate1 = row === rowIndex || col === colIndex;
const classArr = [];
// 是否是填充终点
const validate2 =
endMarkInfo.value?.rowIndex === rowIndex &&
endMarkInfo.value?.colIndex === colIndex;
// 是否是填充起点
const validate3 =
startMarkInfo.value?.rowIndex === rowIndex &&
startMarkInfo.value?.colIndex === colIndex;
// 是否是选区经过点
let validate4 = false;
if (!isEmpty(moveRowColIndeKeyArr.value)) {
const strRowColIndex = rowIndex + "-" + colIndex;
if (moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
validate4 = true;
}
}
// 是否是操作点经过点
let validate5 = false;
if (!isEmpty(pointMoveRowColIndeKeyArr.value)) {
const strRowColIndex = rowIndex + "-" + colIndex;
if (pointMoveRowColIndeKeyArr.value.includes(strRowColIndex)) {
console.log(111, "111");
validate5 = true;
}
}
// 高亮行列
validate1 && classArr.push("highlight-row-col");
// 结束点
validate2 && classArr.push("highlight-end-cell");
// 起始点
validate3 && classArr.push("highlight-start-cell");
// 是否是选区经过点
validate4 && classArr.push("highlight-move-cell");
// 是否是操作点经过点
validate5 && classArr.push("highlight-point-move-cell");
return classArr;
};

// 清除选区标记
const clearStartAndEndMark = () => {
startMarkInfo.value = {
...MARK_INIT_INFO,
};
endMarkInfo.value = {
...MARK_INIT_INFO,
};
moveRowColIndeKeyArr.value = [];
pointMoveRowColIndeKeyArr.value = [];
isDragging.value = false;
operatePointDragger.value = false;
operatePointDragDirection.value = null;
clearOperatePoint();
};

// 鼠标按下标记
const handleMouseDownMark = (param: CellParam) => {
clearStartAndEndMark();
const { rowIndex, colIndex } = param;
startMarkInfo.value = {
rowIndex,
colIndex,
};
isDragging.value = true;
};

// 鼠标移动到cell上,计算经过的cell
const handleMouseMoveMark = (param: CellParam) => {
if (!isDragging.value && !operatePointDragger.value) return;
const { rowIndex, colIndex } = param;

// 得到最后一个经过的cell
// 如果是拖拽操作点,moveRowColIndeKeyArr.value不要重新设置
if (!operatePointDragger.value) {
moveRowColIndeKeyArr.value = [];
}
pointMoveRowColIndeKeyArr.value = [];

// 从起点开始算,经过的cell
const startRowIndex = startMarkInfo.value.rowIndex;
const startColIndex = startMarkInfo.value.colIndex;
const endRowIndex = rowIndex;
const endColIndex = colIndex;
// 判断需要添加的点,
if (isDragging.value) {
// 如果是终点的rowIndex大于起点的rowIndex,则需要添加向下的点
if (endRowIndex >= startRowIndex) {
// 向下
for (let i = startRowIndex; i <= endRowIndex; i++) {
// 判断是向左还是向右
if (endColIndex > startColIndex) {
// 向右
for (let j = startColIndex; j <= endColIndex; j++) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
} else {
// 向左
for (let j = startColIndex; j >= endColIndex; j--) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
}
}
} else if (endRowIndex < startRowIndex) {
// 向上
for (let i = startRowIndex; i >= endRowIndex; i--) {
// 判断是向左还是向右
if (endColIndex > startColIndex) {
// 向右
for (let j = startColIndex; j <= endColIndex; j++) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
} else {
// 向左
for (let j = startColIndex; j >= endColIndex; j--) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
}
}
}
}
// 进行拖拽复制
else if (operatePointDragger.value) {
// 获取操作点当前所在的位置(即选区结束位置)
const operatePointRowIndex = lastMaxMoveRowColIndeKeyArr.value.rowIndex;
const operatePointColIndex = lastMaxMoveRowColIndeKeyArr.value.colIndex;
const endRowIndex = rowIndex;
const endColIndex = colIndex;
// 判断方向,基于操作点位置和当前鼠标位置
const isHorizontal =
Math.abs(endColIndex - operatePointColIndex) >
Math.abs(endRowIndex - operatePointRowIndex);
// 设置操作点拖拽方向
operatePointDragDirection.value = isHorizontal
? "horizontal"
: "vertical";

// 获取原始选区的范围
const originalData = moveRowColIndeKeyArr.value;

// 计算原始选区的行列范围
let originalRowIndices: number[] = [];
let originalColIndices: number[] = [];

originalData.forEach((item) => {
const [rowIndex, colIndex] = item.split("-");
originalRowIndices.push(Number(rowIndex));
originalColIndices.push(Number(colIndex));
});

originalRowIndices = [...new Set(originalRowIndices)].sort(
(a, b) => a - b
);
originalColIndices = [...new Set(originalColIndices)].sort(
(a, b) => a - b
);

// 横向复制
if (isHorizontal && !noHorizontalDrag) {
const isLeft = endColIndex < operatePointColIndex;
if (isLeft) {
// 向左复制:从操作点开始向左扩展,保持原始行数
const colDistance = operatePointColIndex - endColIndex + 1;
for (let colOffset = 0; colOffset < colDistance; colOffset++) {
const targetColIndex = operatePointColIndex - colOffset;
originalRowIndices.forEach((rowIndex) => {
const strRowColIndex = `${rowIndex}-${targetColIndex}`;
// 不在moveRowColIndeKeyArr.value中,才添加
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
} else {
// 向右复制:从操作点开始向右扩展,保持原始行数
const colDistance = endColIndex - operatePointColIndex + 1;
for (let colOffset = 0; colOffset < colDistance; colOffset++) {
const targetColIndex = operatePointColIndex + colOffset;
originalRowIndices.forEach((rowIndex) => {
const strRowColIndex = `${rowIndex}-${targetColIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
}
}
// 纵向复制
else if (!noVerticalDrag && !isHorizontal) {
const isUp = endRowIndex < operatePointRowIndex;
if (isUp) {
// 向上复制:从操作点开始向上扩展,保持原始列数
const rowDistance = operatePointRowIndex - endRowIndex + 1;
for (let rowOffset = 0; rowOffset < rowDistance; rowOffset++) {
const targetRowIndex = operatePointRowIndex - rowOffset;
originalColIndices.forEach((colIndex) => {
const strRowColIndex = `${targetRowIndex}-${colIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
} else {
// 向下复制:从操作点开始向下扩展,保持原始列数
const rowDistance = endRowIndex - operatePointRowIndex + 1;
for (let rowOffset = 0; rowOffset < rowDistance; rowOffset++) {
const targetRowIndex = operatePointRowIndex + rowOffset;
originalColIndices.forEach((colIndex) => {
const strRowColIndex = `${targetRowIndex}-${colIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
}
}
}
};

// 鼠标抬起标记
const handleMouseUpMark = (param: CellParam) => {
const { rowIndex, colIndex } = param;
if (isEmpty(moveRowColIndeKeyArr.value)) {
moveRowColIndeKeyArr.value = [`${rowIndex}-${colIndex}`];
}
if (operatePointDragger.value) {
operatePointDragger.value = false;
}
if (!isDragging.value) {
addOperatePoint();
} else {
isDragging.value = false;
endMarkInfo.value = {
rowIndex,
colIndex,
};
addOperatePoint();
}
// 如果有移动点和框选点
if (
moveRowColIndeKeyArr.value.length > 0 &&
pointMoveRowColIndeKeyArr.value.length > 0
) {
nextTick(() => {
if (!operatePointDragDirection.value) {
operatePointDragDirection.value = "vertical";
}
mouseUpFunc && mouseUpFunc();
});
}
};

// 操作点的mousedown事件处理函数
const handleOperatePointMouseDown = (e: Event) => {
e.preventDefault();
e.stopPropagation();
operatePointDragger.value = true;
};

// 操作点抬起
const handleOperatePointMouseUp = (e: Event) => {
e.preventDefault();
e.stopPropagation();
};

// 处理双击操作点
const handleOperatePointDblClick = (e: Event) => {
e.preventDefault();
e.stopPropagation();
operatePointDragger.value = false;
// 得到最小,最大的x,最大的y
let minR = -1;
let maxR = -1;
let minC = -1;
let maxC = -1;
moveRowColIndeKeyArr.value.forEach((item) => {
const [rowIndex, colIndex] = item.split("-").map(Number);
// 说明是第一次
if (!(~minR && ~maxR && ~maxC && ~minC)) {
minR = rowIndex;
maxR = rowIndex;
maxC = colIndex;
minC = colIndex;
} else {
minR = Math.min(minR, rowIndex);
maxR = Math.max(maxR, rowIndex);
maxC = Math.max(maxC, colIndex);
minC = Math.min(minC, colIndex);
}
});
// 只有一列
if (minC === maxC) {
const tableData = getTableData();
const columns = getColumns();
const curColKey = columns[maxC]?.colKey;
let fIndex = 0;
for (let rowIndex = maxR + 1; rowIndex < tableData.length; rowIndex++) {
if (tableData[rowIndex][curColKey]) {
fIndex = rowIndex - 1;
break;
} else {
pointMoveRowColIndeKeyArr.value.push(`${rowIndex}-${maxC}`);
}
}
fIndex = tableData.length - 1;
handleMouseUpMark({
rowIndex: fIndex,
colIndex: minC,
});
}
};

// 去除操作点
const clearOperatePoint = () => {
const operatePoint = document.querySelector(`.${key}operate-point`);
if (operatePoint) {
operatePoint.addEventListener("mouseup", handleOperatePointMouseUp);
operatePoint.removeEventListener(
"mousedown",
handleOperatePointMouseDown
);
operatePoint.removeEventListener("dblclick", handleOperatePointDblClick);
operatePoint.remove();
operatePointDragger.value = false;
}
};

// 添加操作点
const addOperatePoint = () => {
clearOperatePoint();
nextTick(() => {
const operatePoint = document.createElement("div");
operatePoint.className = `${key}operate-point`;
operatePoint.style.position = "absolute";
operatePoint.style.bottom = "-2.5px";
operatePoint.style.right = "-2.5px";
operatePoint.style.width = "8px";
operatePoint.style.height = "8px";
operatePoint.style.backgroundColor =
operatePointColor || "var(--td-brand-color-5)";
operatePoint.style.cursor = "crosshair";
operatePoint.style.zIndex = "100";
const cellDom = document.querySelector(`.highlight-end-cell`);
if (cellDom) {
cellDom.appendChild(operatePoint);
// 给这个点添加doubleclick事件
operatePoint.addEventListener("dblclick", handleOperatePointDblClick);
// 给这个点添加mouseup事件,避免直接触发handleMouseUpMark事件
operatePoint.addEventListener("mouseup", handleOperatePointMouseUp);
// 给这个点添加mousedown事件
operatePoint.addEventListener("mousedown", handleOperatePointMouseDown);
}
});
};

// 点击自动聚焦
const handleClickCellToFocus = (rowIndex: number, colIndex: number) => {
nextTick(() => {
const id = `#${key}${rowIndex}-${colIndex}`;
const parentDom = document.querySelector(id);
if (parentDom) {
const inputDom = parentDom.querySelector(
".t-input__inner"
) as HTMLInputElement;
inputDom.focus();
inputDom.setSelectionRange(0, String(inputDom.value).length);
}
});
};

// 复制选区内容
const copySelectionToClipboard = () => {
const columns = getColumns();
const tableData = getTableData();
if (!moveRowColIndeKeyArr.value.length) return;
// 解析所有选中的 row/col
const cellList = moveRowColIndeKeyArr.value.map((str) => {
const [row, col] = str.split("-").map(Number);
return { row, col };
});
// 计算选区的最小/最大行列
const rows = cellList.map((c) => c.row);
const cols = cellList.map((c) => c.col);
const minRow = Math.min(...rows),
maxRow = Math.max(...rows);
const minCol = Math.min(...cols),
maxCol = Math.max(...cols);

// 构造二维数组
let result: string[][] = [];
for (let i = minRow; i <= maxRow; i++) {
let rowArr: string[] = [];
for (let j = minCol; j <= maxCol; j++) {
if (moveRowColIndeKeyArr.value.includes(`${i}-${j}`)) {
let colKey = columns[j].colKey;
rowArr.push(tableData[i][colKey]);
} else {
rowArr.push("");
}
}
result.push(rowArr);
}
// 转为 Excel 兼容的文本
const text = result.map((row) => row.join("\t")).join("\n");
if (text) {
handleCopy({
text: text.trim(),
});
} else {
NotifyPlugin.error({
title: "无内容复制",
});
}
};

// 删除选区内容
const deleteSelection = () => {
if (!onDeleteCell) return;
const columns = getColumns();
moveRowColIndeKeyArr.value.forEach((item) => {
const [rowIndex, colIndex] = item.split("-").map(Number);
let colKey = columns[colIndex]?.colKey;
if (colKey) {
onDeleteCell(rowIndex, colKey);
}
});
};

// 粘贴选区内容
const pasteClipboardToSelection = async (
onPasteCell: (rowIndex: number, colKey: string, value: string) => void,
text: string
) => {
const columns = getColumns();
if (!moveRowColIndeKeyArr.value.length) return;
if (!text) return;
const rows = text.split(/\r?\n/).map((row) => row.split("\t"));
const cellList = moveRowColIndeKeyArr.value.map((str) => {
const [row, col] = str.split("-").map(Number);
return { row, col };
});
let flatValues: string[] = [];
for (let i = 0; i < rows.length; i++)
for (let j = 0; j < rows[i].length; j++) flatValues.push(rows[i][j]);
for (let i = 0; i < cellList.length; i++) {
const { row, col } = cellList[i];
let colKey = columns[col]?.colKey;
if (colKey) {
const value = flatValues[i] ?? "";
onPasteCell(row, colKey, value.trim());
}
}
};

// 处理键盘事件
const handleKeydown = async (e: KeyboardEvent) => {
// Ctrl+C / Cmd+C: 复制
if ((e.ctrlKey || e.metaKey) && e.key === "c") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length > 0) {
e.preventDefault();
copySelectionToClipboard();
}
}
// Backspace: 删除
else if (e.key === "Backspace") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length > 1) {
e.preventDefault();
deleteSelection();
}
}
};

return {
curNeedHighLightRowAndCol,
handleHighlight,
getHighlightColorClass,
handleClickCellToFocus,
addOperatePoint,
handleMouseDownMark,
handleMouseMoveMark,
handleMouseUpMark,
handleKeydown,
moveRowColIndeKeyArr,
pasteClipboardToSelection,
};
}

处理 mouseup 事件,赋值

我这里在 hook 中写了一个根据框选内容和操作点经过内容进行判断的简单逻辑,因为我这里不完全是 excel 那种需要根据 excel 的数字进行累加的逻辑,我只需要根据内容进行复制,如果你有啥其他的需要,可以修改这个方法的代码,这里我留了横向的没写,大家可以自己去完善。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// 获取需要赋值的数据
const getNeedGiftData = () => {
const columns = getColumns();
const tableData = getTableData();
const needGiftData: {
colKey: string;
rowIndex: number;
data: string;
}[] = [] as any;
if (
!isEmpty(moveRowColIndeKeyArr.value) &&
operatePointDragDirection.value === "vertical"
) {
const colToColKeyDataRowMap = new Map<
number,
{
colKey: string;
curData: string[];
rowIndex: number[];
}
>();
for (let i = 0; i < moveRowColIndeKeyArr.value.length; i++) {
const [rowIndex, colIndex] = moveRowColIndeKeyArr.value[i]
.split("-")
.map(Number);
const curColKey = columns[colIndex]?.colKey;
if (curColKey) {
const curColKeyFitData = tableData[rowIndex][curColKey];
if (!colToColKeyDataRowMap.has(colIndex)) {
colToColKeyDataRowMap.set(colIndex, {
colKey: curColKey,
curData: [],
rowIndex: [],
});
}
const curColKeyDataRowMap = colToColKeyDataRowMap.get(colIndex);
if (curColKeyDataRowMap) {
curColKeyDataRowMap.curData.push(curColKeyFitData);
curColKeyDataRowMap.rowIndex.push(rowIndex);
}
}
}
const calColIndexNumMap = new Map<number, number>();
pointMoveRowColIndeKeyArr.value.forEach((item, index) => {
const [pRowIndex, colIndex] = item.split("-").map(Number);
const curColKeyDataRowMap = colToColKeyDataRowMap.get(colIndex);
if (curColKeyDataRowMap) {
calColIndexNumMap.set(
colIndex,
(calColIndexNumMap.get(colIndex) || 0) + 1
);
const count = calColIndexNumMap.get(colIndex) || 0;
const curGiftItem =
curColKeyDataRowMap.curData[
(count - 1) % curColKeyDataRowMap.curData.length
];
let curColKey = curColKeyDataRowMap.colKey;
needGiftData.push({
colKey: curColKey,
rowIndex: pRowIndex,
data: curGiftItem,
});
}
});
}
return needGiftData;
};

在组件中进行赋值逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 赋值
const excelInputHandle = () => {
if (!isEmpty(moveRowColIndeKeyArr.value)) {
const needGiftData = getNeedGiftData();
needGiftData.forEach((item) => {
const { rowIndex, colKey, data } = item;
/**
* 处理你的赋值逻辑
*/
tableData.value[rowIndex][colKey] = data;
});
setPointMoveRowColIndeKeyArrToMoveRowColIndeKeyArr();
}
};

赋值完成之后,需要将内容重新框起来

在 hook 中添加

1
2
3
4
5
6
7
8
9
10
11
// 将pointMoveRowColIndeKeyArr的点位合并,设置成moveRowColIndeKeyArr的点位,去重
const setPointMoveRowColIndeKeyArrToMoveRowColIndeKeyArr = () => {
moveRowColIndeKeyArr.value = [
...new Set([
...moveRowColIndeKeyArr.value,
...pointMoveRowColIndeKeyArr.value,
]),
];
pointMoveRowColIndeKeyArr.value = [];
addOperatePoint();
};

双击小点进行空值同列单元格赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 处理双击操作点
const handleOperatePointDblClick = (e: Event) => {
e.preventDefault();
e.stopPropagation();
operatePointDragger.value = false;
// 得到最小,最大的x,最大的y
let minR = -1;
let maxR = -1;
let minC = -1;
let maxC = -1;
moveRowColIndeKeyArr.value.forEach((item) => {
const [rowIndex, colIndex] = item.split("-").map(Number);
// 说明是第一次
if (!(~minR && ~maxR && ~maxC && ~minC)) {
minR = rowIndex;
maxR = rowIndex;
maxC = colIndex;
minC = colIndex;
} else {
minR = Math.min(minR, rowIndex);
maxR = Math.max(maxR, rowIndex);
maxC = Math.max(maxC, colIndex);
minC = Math.min(minC, colIndex);
}
});
// 只有一列
if (minC === maxC) {
const tableData = getTableData();
const columns = getColumns();
const curColKey = columns[maxC]?.colKey;
let fIndex = 0;
for (let rowIndex = maxR + 1; rowIndex < tableData.length; rowIndex++) {
if (tableData[rowIndex][curColKey]) {
fIndex = rowIndex - 1;
break;
} else {
pointMoveRowColIndeKeyArr.value.push(`${rowIndex}-${maxC}`);
}
}
fIndex = tableData.length - 1;
handleMouseUpMark({
rowIndex: fIndex,
colIndex: minC,
});
}
};

此时效果如下

核心的其实到这里就已经说完了的,上面视频我只展示了单行的,其实多行单列也是支持的了,横向复制的逻辑,我因为自己没用,所以我就没写这个的,传 hook 的时候,我都是带上noHorizontalDrag: true,你如果需要的话,完全可以根据我的getNeedGiftData方法的逻辑进行完善,我后续有时间的话应该会写的,但是单独发博客是不会发了的,你如果搞不定,可以来联系我。

需求 8:点击表头选中列,点击序号选中行

在 hook 加上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 手动设置当前选区
const setMoveRowColIndeKeyArr = (pointArr: string[]) => {
clearStartAndEndMark();
moveRowColIndeKeyArr.value = [...new Set([...pointArr])];
pointMoveRowColIndeKeyArr.value = [];
addOperatePoint();
};

// 默认选中列
const setMoveRowColCurrentCol = (colIndex: number) => {
const tableData = getTableData();
const pointArr: string[] = [];
tableData.forEach((_, index) => {
pointArr.push(`${index}-${colIndex}`);
});
setMoveRowColIndeKeyArr(pointArr);
};

// 默认选中行
const setMoveRowColCurrentRow = (param: {
rowIndex: number;
filterKeys: string[];
}) => {
const { rowIndex, filterKeys } = param;
const columnData = getColumns().filter(
(item) => !filterKeys.includes(item.colKey)
);
const pointArr: string[] = [];
columnData.forEach((_, index) => {
pointArr.push(`${rowIndex}-${index}`);
});
setMoveRowColIndeKeyArr(pointArr);
};

如果你的 table 需要更多逻辑判断,可以自己生成选中的点,然后使用setMoveRowColIndeKeyArr直接赋值,而不是用我现成的这俩个方法,最终实现效果大概如下

需求 9:方向键,tab,回车键调整选中单元格

最后我们说一下通过按键进行单元格调整,这里我也不多说了,挺简单的,我直接贴代码好了

事件监听

在 hook 的 handleKeyDown 中添加事件监听,但是只监听选中一个单元格的时候

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 处理键盘事件
const handleKeydown = async (e: KeyboardEvent) => {
// Ctrl+C / Cmd+C: 复制
if ((e.ctrlKey || e.metaKey) && e.key === "c") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length > 0) {
e.preventDefault();
copySelectionToClipboard();
}
}
// Backspace: 删除
else if (e.key === "Backspace") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length > 1) {
e.preventDefault();
deleteSelection();
}
}
// tab键
else if (e.key === "Tab") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length === 1) {
e.preventDefault();
handleTabKeyEnter();
}
}
// 上下左右键
else if (
e.key === "ArrowUp" ||
e.key === "ArrowDown" ||
e.key === "ArrowLeft" ||
e.key === "ArrowRight"
) {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length === 1) {
e.preventDefault();
handleArrowKeyEnter(e.key);
}
}
// 回车键
else if (e.key === "Enter") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length === 1) {
e.preventDefault();
handleEnterKeyEnter();
}
}
};

事件

这里我传递下来了onTabKeyEnter,onArrowKeyEnter,onEnterKeyEnter事件,因为我部分单元格回车有自己的事件,要查接口,接口成功才可以跳,所以给加了个await onEnterKeyEnter,然后这里的id其实就是那个no-edit-cell不编辑单元格,给每个单元格加个id方便我跳转,disabled是因为我自己的逻辑里面,并不是所有单元格都是可编辑的,我定义的是disabled的 class,就是跳格子的时候忽略这个class的格子,其他的逻辑也没怎么复杂。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// 处理tab键-横向移动
const handleTabKeyEnter = () => {
if (!onTabKeyEnter) return;
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
const tableData = getTableData();
const columns = getColumns();
// 检查是否已经到达表格末尾
if (
curRowIndex === tableData.length - 1 &&
curColIndex === columns.length - 1
) {
// 已经是最后一个单元格,不进行跳转
return;
}

// 开始寻找下一个可用的单元格
let foundValidCell = false;
let maxAttempts = tableData.length * columns.length; // 防止无限循环
let attempts = 0;

while (!foundValidCell && attempts < maxAttempts) {
attempts++;

// 移动到下一个单元格
curColIndex++;

// 如果当前列超出范围,移动到下一行
if (curColIndex >= columns.length) {
curColIndex = 0; // 重置到第一列(跳过第0列)
curRowIndex++;
}

// 检查是否超出表格范围
if (curRowIndex >= tableData.length) {
// 已经超出表格范围,停止查找
break;
}

// 尝试获取单元格DOM
let id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
let dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");

// 检查单元格是否可用(存在且不是disabled)
if (dom && !domClass?.includes("disabled")) {
foundValidCell = true;
// 执行跳转
onTabKeyEnter && onTabKeyEnter();
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}

// 如果没有找到有效的单元格,可以选择不执行任何操作或给出提示
if (!foundValidCell) {
console.log("没有找到下一个可用的单元格");
}
};

// 处理上下左右键
const handleArrowKeyEnter = (key: string) => {
if (!onArrowKeyEnter) return;
// 如果是上键,往上移动,但是遇到没有dom或者dom是disabled的,则再往上移动
if (key === "ArrowUp") {
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
while (curRowIndex > 0) {
curRowIndex--;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
break;
}
}
if (curRowIndex >= 0 && dom) {
onArrowKeyEnter && onArrowKeyEnter(key);
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}
// 如果是下键,往下移动,但是遇到没有dom或者dom是disabled的,则再往下移动
else if (key === "ArrowDown") {
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
const tableData = getTableData();
while (curRowIndex < tableData.length - 1) {
curRowIndex++;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
break;
}
}
if (curRowIndex < tableData.length && dom) {
onArrowKeyEnter && onArrowKeyEnter(key);
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}
// 如果是左键,往左移动,但是遇到没有dom或者dom是disabled的,则再往左移动
else if (key === "ArrowLeft") {
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
while (curColIndex > 0) {
curColIndex--;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
break;
}
}
if (curColIndex >= 0 && dom) {
onArrowKeyEnter && onArrowKeyEnter(key);
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}
// 如果是右键,往右移动,但是遇到没有dom或者dom是disabled的,则再往右移动
else if (key === "ArrowRight") {
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
const columns = getColumns();
while (curColIndex < columns.length - 1) {
curColIndex++;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
break;
}
}
if (curColIndex < columns.length && dom) {
onArrowKeyEnter && onArrowKeyEnter(key);
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}
};

// 处理回车键
const handleEnterKeyEnter = async () => {
if (!onEnterKeyEnter) return;
// 回车键向下移动,遇到disabled或者没有dom,继续向下移动,然后到最底下的时候,把rowIndex变成0,colIndex+1,继续向下移动,当移动到最后一个单元格的时候,也就是rowIndex=tableData.length-1,colIndex=columns.length-1,停止移动,参考tab的横向移动,这里只是把这个横向改成纵向了
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
const tableData = getTableData();
const columns = getColumns();
// 检查是否已经到达表格末尾
if (
curRowIndex === tableData.length - 1 &&
curColIndex === columns.length - 1
) {
// 已经是最后一个单元格,不进行跳转
return;
}
let foundValidCell = false;
let maxAttempts = tableData.length * columns.length; // 防止无限循环
let attempts = 0;
while (!foundValidCell && attempts < maxAttempts) {
attempts++;
curRowIndex++;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
foundValidCell = true;
} else {
if (curRowIndex >= tableData.length) {
curRowIndex = -1;
curColIndex++;
}
}
}
if (foundValidCell) {
await onEnterKeyEnter();
if (dom) {
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
} else {
console.error("没有找到下一个可用的单元格");
}
};

完整代码

vue 组件文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
<template>
<div class="excel-table">
<t-table
:columns="columns"
row-key="id"
:data="tableData"
max-height="95vh"
bordered
@paste="handlePaste"
>
<!-- 操作表头自定义 -->
<template v-for="item in tableTitles" :key="item" #[item]="{ colIndex }">
<div @click="setMoveRowColCurrentCol(colIndex)">{{ item }}</div>
</template>
<!-- 序号列,自定义 -->
<template #gNo="{ row, rowIndex }">
<div
@click="
setMoveRowColCurrentRow({
rowIndex,
filterKeys: ['gNo'],
})
"
>
{{ row.gNo }}
</div>
</template>
<!-- 插槽自定义渲染单元格 -->
<template
v-for="item in tableColKeys.slice(1)"
:key="item"
#[item]="{ row, col, rowIndex, colIndex }"
>
<div
:class="
isDisabled(rowIndex, colIndex)
? ''
: getCellHighlightColorClass(rowIndex, colIndex)
"
@mousedown.stop="
handleMouseDownMark({
rowIndex,
colIndex,
})
"
@mouseup.stop="
handleMouseUpMark({
rowIndex,
colIndex,
})
"
@mousemove.stop="
handleMouseMoveMark({
rowIndex,
colIndex,
})
"
>
<div v-if="isEditing(rowIndex, colIndex)">
<t-input
v-model="row[item]"
placeholder=""
:id="`${ELEMENT_KEY}${rowIndex}-${colIndex}`"
></t-input>
</div>
<div
v-else
class="no-edit-cell"
@click="handleCellClick({ rowIndex, colIndex })"
:id="`${ELEMENT_KEY}-no-edit-cell-${rowIndex}-${colIndex}`"
:class="{
disabled: isDisabled(rowIndex, colIndex),
}"
>
{{ row[item] }}
</div>
</div>
</template>
</t-table>
</div>
</template>
<script setup>
import { computed, onMounted, ref, nextTick, onBeforeUnmount } from "vue";
import { useExcelSelection } from "@/hooks/useExcelSelection";
import { isEmpty } from "lodash";

// table列
const columns = ref([]);

// table的colKey
const tableColKeys = computed(() => {
return columns.value.map((item) => item.colKey);
});

// table的title
const tableTitles = computed(() => {
const titles = [];
columns.value.forEach((item) => {
if (item.title !== "序号") {
titles.push(item.title);
}
});
return titles;
});

// 需要disable的key
const needDisabledKey = ["1-2"];
const isDisabled = (rowIndex, colIndex) => {
const strRowColIndex = `${rowIndex}-${colIndex}`;
return needDisabledKey.includes(strRowColIndex);
};

// table数据
const tableData = ref([]);

// 初始化列
const initColumns = () => {
const arr = [{ colKey: "gNo", title: "序号", width: 80 }];
for (let i = 65; i <= 90; i++) {
const key = String.fromCharCode(i);
arr.push({
title: key,
colKey: key + "colKey",
width: 100,
});
}
columns.value = arr;
};

// 初始化table数据
const initTableData = () => {
const arr = [];
for (let i = 0; i <= 50; i++) {
const eachData = {
gNo: i + 1,
};
for (let j = 65; j <= 90; j++) {
const key = String.fromCharCode(j);
eachData[key + "colKey"] = key + i;
}
arr.push(eachData);
}
tableData.value = arr;
};

onMounted(() => {
initTableData();
initColumns();
});

onMounted(() => {
document
.querySelector(".excel-table")
.addEventListener("keydown", handleKeydown);
});
onBeforeUnmount(() => {
document
.querySelector(".excel-table")
.removeEventListener("keydown", handleKeydown);
});

// 删除单元格回调
const handleDeleteCell = (rowIndex, colKey) => {
/**
* 处理你的清空内容逻辑
*/
tableData.value[rowIndex][colKey] = "";
};

// 赋值
const excelInputHandle = () => {
if (!isEmpty(moveRowColIndeKeyArr.value)) {
const needGiftData = getNeedGiftData();
needGiftData.forEach((item) => {
const { rowIndex, colKey, data } = item;
/**
* 处理你的赋值逻辑
*/
tableData.value[rowIndex][colKey] = data;
});
setPointMoveRowColIndeKeyArrToMoveRowColIndeKeyArr();
}
};

const ELEMENT_KEY = "batchTableInput";
const excelSelection = useExcelSelection({
key: ELEMENT_KEY,
noHorizontalDrag: true,
operatePointColor: "var(--td-success-color-5)",
getColumns: () => columns.value,
getTableData: () => tableData.value,
onDeleteCell: handleDeleteCell,
mouseUpFunc: excelInputHandle,
onTabKeyEnter: () => {},
onArrowKeyEnter: (key) => {},
onEnterKeyEnter: () => {
// return new Promise((resolve,reject)=>{
// })
},
});
const {
curNeedHighLightRowAndCol,
handleHighlight,
getHighlightColorClass,
handleClickCellToFocus,
handleMouseDownMark,
handleMouseUpMark,
handleMouseMoveMark,
handleKeydown,
moveRowColIndeKeyArr,
pasteClipboardToSelection,
getNeedGiftData,
setPointMoveRowColIndeKeyArrToMoveRowColIndeKeyArr,
setMoveRowColCurrentRow,
setMoveRowColCurrentCol,
} = excelSelection;

// 点击单元格
const handleCellClick = (param) => {
const { colIndex, rowIndex } = param;
if (isDisabled(rowIndex, colIndex)) return;
handleHighlight(rowIndex, colIndex);
handleClickCellToFocus(rowIndex, colIndex);
};

// 选区粘贴内容
function handlePasteCell(rowIndex, colKey, value) {
/**
* 处理你的复制赋值逻辑
*/
tableData.value[rowIndex][colKey] = value;
}

// 粘贴
function handlePaste(e) {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length >= 1) {
let text = e.clipboardData?.getData("text");
if (text) {
pasteClipboardToSelection(handlePasteCell, text);
e.preventDefault(); // 阻止默认粘贴行为
}
}
}

// 获取class样式
const getCellHighlightColorClass = (rowIndex, colIndex) => {
// 总的颜色类
let classArr = [];
/**
* 处理非excel的,自己的逻辑,加上颜色类
*/
// excel颜色类
const excelColor = getHighlightColorClass(rowIndex, colIndex);
// 拼接excel颜色类
classArr = classArr.concat(excelColor);
const str = classArr.join(" ");
return str;
};

// 是否在编辑状态
const isEditing = (rowIndex, colIndex) => {
const { row, col } = curNeedHighLightRowAndCol;
const validate1 = row === rowIndex && col === colIndex;
// 这里可以加上你需要的逻辑等
return Boolean(validate1);
};
</script>
<style lang="less">
body {
--batchHighlightColor: #e6f1ff;
}
.excel-table {
.t-table__content {
user-select: none;
}
.t-table th,
.t-table td {
padding: 0;
}
.t-table--bordered td,
.t-table--bordered th {
box-sizing: border-box;
}

.t-table__body .t-input,
.t-table__body .t-input--focused {
border: none;
box-shadow: none;
}

.highlight-row-col {
background-color: var(--batchHighlightColor) !important;
.t-input,
.t-input__inner {
background-color: var(--batchHighlightColor) !important;
}
}

.highlight-end-cell,
.highlight-move-cell,
.highlight-start-cell,
.highlight-point-move-cell {
box-sizing: border-box !important;
border: 2px solid var(--td-success-color-5) !important;
.t-input,
.t-input__inner {
height: 28px !important;
}
.no-edit-cell {
height: 28px !important;
line-height: 28px !important;
}
}
.highlight-point-move-cell {
border-color: var(--td-error-color) !important;
}
}
</style>
<style scoped lang="less">
.excel-table {
margin: 0;
padding: 0;
background: #f5f5f5;
}

.no-edit-cell {
height: 32px;
line-height: 32px;
padding: 0 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

.disabled {
background-color: var(--td-bg-color-component-disabled);
color: #333;
cursor: not-allowed;
height: 32px;
line-height: 32px;
}
</style>

hook 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
import { reactive, nextTick, ref, computed } from "vue";
import { isEmpty } from "lodash";
import { NotifyPlugin } from "tdesign-vue-next";
import useClipboard from "vue-clipboard3";

export const MARK_INIT_INFO = {
rowIndex: -1,
colIndex: -1,
};

export interface MarkInfo {
rowIndex: number;
colIndex: number;
}

export interface CellParam {
rowIndex: number;
colIndex: number;
}

export const handleCopy = (param: {
text: string;
successMsg?: string;
errorMsg?: string;
}) => {
const { text, successMsg, errorMsg } = param;
const sourceText = text;
const successMessage = successMsg || "复制成功";
const errorMessage = errorMsg || "复制失败";
const { toClipboard } = useClipboard();
toClipboard(sourceText)
.then(() => {
NotifyPlugin.closeAll();
NotifyPlugin.success({
title: successMessage,
});
})
.catch(() => {
NotifyPlugin.closeAll();
NotifyPlugin.error({
title: errorMessage,
});
});
};

export function useExcelSelection(
config: Partial<{
// 标识id
key: string;
// 不许横向拖拽操作点
noHorizontalDrag?: boolean;
// 不许纵向拖拽操作点
noVerticalDrag?: boolean;
// 鼠标抬起时回调
mouseUpFunc: any;
// 操作点颜色
operatePointColor: string;
// 表格列配置获取函数
getColumns: () => any[];
// 表格数据获取函数
getTableData: () => any[];
// 删除单元格回调
onDeleteCell?: (rowIndex: number, colKey: string) => void;
// tab键回调
onTabKeyEnter?: () => void;
// 上下左右键回调
onArrowKeyEnter?: (key: string) => void;
// 回车键回调
onEnterKeyEnter?: () => void;
}>
) {
const {
key,
operatePointColor,
getColumns,
getTableData,
onDeleteCell,
noHorizontalDrag = false,
noVerticalDrag = false,
mouseUpFunc,
onTabKeyEnter,
onArrowKeyEnter,
onEnterKeyEnter,
} = config;

// 开始的标记
const startMarkInfo = ref<MarkInfo>({
...MARK_INIT_INFO,
});

// 拖拽选区经过的cell
const moveRowColIndeKeyArr = ref<string[]>([]);

// 拖拽操作点经过的cell
const pointMoveRowColIndeKeyArr = ref<string[]>([]);

// 操作点拖拽方向
const operatePointDragDirection = ref<"horizontal" | "vertical" | null>(null);

// 结束的标记
const endMarkInfo = ref<MarkInfo>({
...MARK_INIT_INFO,
});

// 是否在拖拽选区
const isDragging = ref(false);

// 是否是根据操作点在拖拽
const operatePointDragger = ref(false);

// 当前高亮的点
const curNeedHighLightRowAndCol = reactive({
row: -1,
col: -1,
});

// 获取需要赋值的数据
const getNeedGiftData = () => {
const columns = getColumns();
const tableData = getTableData();
const needGiftData: {
colKey: string;
rowIndex: number;
data: string;
}[] = [] as any;
if (
!isEmpty(moveRowColIndeKeyArr.value) &&
operatePointDragDirection.value === "vertical"
) {
const colToColKeyDataRowMap = new Map<
number,
{
colKey: string;
curData: string[];
rowIndex: number[];
}
>();
for (let i = 0; i < moveRowColIndeKeyArr.value.length; i++) {
const [rowIndex, colIndex] = moveRowColIndeKeyArr.value[i]
.split("-")
.map(Number);
const curColKey = columns[colIndex]?.colKey;
if (curColKey) {
const curColKeyFitData = tableData[rowIndex][curColKey];
if (!colToColKeyDataRowMap.has(colIndex)) {
colToColKeyDataRowMap.set(colIndex, {
colKey: curColKey,
curData: [],
rowIndex: [],
});
}
const curColKeyDataRowMap = colToColKeyDataRowMap.get(colIndex);
if (curColKeyDataRowMap) {
curColKeyDataRowMap.curData.push(curColKeyFitData);
curColKeyDataRowMap.rowIndex.push(rowIndex);
}
}
}
const calColIndexNumMap = new Map<number, number>();
pointMoveRowColIndeKeyArr.value.forEach((item, index) => {
const [pRowIndex, colIndex] = item.split("-").map(Number);
const curColKeyDataRowMap = colToColKeyDataRowMap.get(colIndex);
if (curColKeyDataRowMap) {
calColIndexNumMap.set(
colIndex,
(calColIndexNumMap.get(colIndex) || 0) + 1
);
const count = calColIndexNumMap.get(colIndex) || 0;
const curGiftItem =
curColKeyDataRowMap.curData[
(count - 1) % curColKeyDataRowMap.curData.length
];
let curColKey = curColKeyDataRowMap.colKey;
needGiftData.push({
colKey: curColKey,
rowIndex: pRowIndex,
data: curGiftItem,
});
}
});
}
return needGiftData;
};

// 拖拽选区经过的cell的最大行和列
const lastMaxMoveRowColIndeKeyArr = computed(() => {
// 根据moveRowColIndexKeyArr进行计算
const data = moveRowColIndeKeyArr.value;
let maxRowIndex = -1;
let maxColIndex = -1;
data.forEach((item) => {
const [rowIndex, colIndex] = item.split("-");
maxRowIndex = Math.max(maxRowIndex, Number(rowIndex));
maxColIndex = Math.max(maxColIndex, Number(colIndex));
});
return {
rowIndex: maxRowIndex,
colIndex: maxColIndex,
};
});

// 点击处理高亮
const handleHighlight = (rowIndex: number, colIndex: number) => {
curNeedHighLightRowAndCol.row = rowIndex;
curNeedHighLightRowAndCol.col = colIndex;
};

// 获取样式
const getHighlightColorClass = (rowIndex: number, colIndex: number) => {
const { row, col } = curNeedHighLightRowAndCol;
// 是否高亮行列
const validate1 = row === rowIndex || col === colIndex;
const classArr = [];
// 是否是填充终点
const validate2 =
endMarkInfo.value?.rowIndex === rowIndex &&
endMarkInfo.value?.colIndex === colIndex;
// 是否是填充起点
const validate3 =
startMarkInfo.value?.rowIndex === rowIndex &&
startMarkInfo.value?.colIndex === colIndex;
// 是否是选区经过点
let validate4 = false;
if (!isEmpty(moveRowColIndeKeyArr.value)) {
const strRowColIndex = rowIndex + "-" + colIndex;
if (moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
validate4 = true;
}
}
// 是否是操作点经过点
let validate5 = false;
if (!isEmpty(pointMoveRowColIndeKeyArr.value)) {
const strRowColIndex = rowIndex + "-" + colIndex;
if (pointMoveRowColIndeKeyArr.value.includes(strRowColIndex)) {
validate5 = true;
}
}
// 高亮行列
validate1 && classArr.push("highlight-row-col");
// 结束点
validate2 && classArr.push("highlight-end-cell");
// 起始点
validate3 && classArr.push("highlight-start-cell");
// 是否是选区经过点
validate4 && classArr.push("highlight-move-cell");
// 是否是操作点经过点
validate5 && classArr.push("highlight-point-move-cell");
return classArr;
};

// 清除选区标记
const clearStartAndEndMark = () => {
startMarkInfo.value = {
...MARK_INIT_INFO,
};
endMarkInfo.value = {
...MARK_INIT_INFO,
};
moveRowColIndeKeyArr.value = [];
pointMoveRowColIndeKeyArr.value = [];
isDragging.value = false;
operatePointDragger.value = false;
operatePointDragDirection.value = null;
clearOperatePoint();
};

// 鼠标按下标记
const handleMouseDownMark = (param: CellParam) => {
clearStartAndEndMark();
const { rowIndex, colIndex } = param;
startMarkInfo.value = {
rowIndex,
colIndex,
};
isDragging.value = true;
};

// 鼠标移动到cell上,计算经过的cell
const handleMouseMoveMark = (param: CellParam) => {
if (!isDragging.value && !operatePointDragger.value) return;
const { rowIndex, colIndex } = param;

// 得到最后一个经过的cell
// 如果是拖拽操作点,moveRowColIndeKeyArr.value不要重新设置
if (!operatePointDragger.value) {
moveRowColIndeKeyArr.value = [];
}
pointMoveRowColIndeKeyArr.value = [];

// 从起点开始算,经过的cell
const startRowIndex = startMarkInfo.value.rowIndex;
const startColIndex = startMarkInfo.value.colIndex;
const endRowIndex = rowIndex;
const endColIndex = colIndex;
// 判断需要添加的点,
if (isDragging.value) {
// 如果是终点的rowIndex大于起点的rowIndex,则需要添加向下的点
if (endRowIndex >= startRowIndex) {
// 向下
for (let i = startRowIndex; i <= endRowIndex; i++) {
// 判断是向左还是向右
if (endColIndex > startColIndex) {
// 向右
for (let j = startColIndex; j <= endColIndex; j++) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
} else {
// 向左
for (let j = startColIndex; j >= endColIndex; j--) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
}
}
} else if (endRowIndex < startRowIndex) {
// 向上
for (let i = startRowIndex; i >= endRowIndex; i--) {
// 判断是向左还是向右
if (endColIndex > startColIndex) {
// 向右
for (let j = startColIndex; j <= endColIndex; j++) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
} else {
// 向左
for (let j = startColIndex; j >= endColIndex; j--) {
const strRowColIndex = `${i}-${j}`;
moveRowColIndeKeyArr.value.push(strRowColIndex);
}
}
}
}
}
// 进行拖拽复制
else if (operatePointDragger.value) {
// 获取操作点当前所在的位置(即选区结束位置)
const operatePointRowIndex = lastMaxMoveRowColIndeKeyArr.value.rowIndex;
const operatePointColIndex = lastMaxMoveRowColIndeKeyArr.value.colIndex;
const endRowIndex = rowIndex;
const endColIndex = colIndex;
// 判断方向,基于操作点位置和当前鼠标位置
const isHorizontal =
Math.abs(endColIndex - operatePointColIndex) >
Math.abs(endRowIndex - operatePointRowIndex);
// 设置操作点拖拽方向
operatePointDragDirection.value = isHorizontal
? "horizontal"
: "vertical";

// 获取原始选区的范围
const originalData = moveRowColIndeKeyArr.value;

// 计算原始选区的行列范围
let originalRowIndices: number[] = [];
let originalColIndices: number[] = [];

originalData.forEach((item) => {
const [rowIndex, colIndex] = item.split("-");
originalRowIndices.push(Number(rowIndex));
originalColIndices.push(Number(colIndex));
});

originalRowIndices = [...new Set(originalRowIndices)].sort(
(a, b) => a - b
);
originalColIndices = [...new Set(originalColIndices)].sort(
(a, b) => a - b
);

// 横向复制
if (isHorizontal && !noHorizontalDrag) {
const isLeft = endColIndex < operatePointColIndex;
if (isLeft) {
// 向左复制:从操作点开始向左扩展,保持原始行数
const colDistance = operatePointColIndex - endColIndex + 1;
for (let colOffset = 0; colOffset < colDistance; colOffset++) {
const targetColIndex = operatePointColIndex - colOffset;
originalRowIndices.forEach((rowIndex) => {
const strRowColIndex = `${rowIndex}-${targetColIndex}`;
// 不在moveRowColIndeKeyArr.value中,才添加
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
} else {
// 向右复制:从操作点开始向右扩展,保持原始行数
const colDistance = endColIndex - operatePointColIndex + 1;
for (let colOffset = 0; colOffset < colDistance; colOffset++) {
const targetColIndex = operatePointColIndex + colOffset;
originalRowIndices.forEach((rowIndex) => {
const strRowColIndex = `${rowIndex}-${targetColIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
}
}
// 纵向复制
else if (!noVerticalDrag && !isHorizontal) {
const isUp = endRowIndex < operatePointRowIndex;
if (isUp) {
// 向上复制:从操作点开始向上扩展,保持原始列数
const rowDistance = operatePointRowIndex - endRowIndex + 1;
for (let rowOffset = 0; rowOffset < rowDistance; rowOffset++) {
const targetRowIndex = operatePointRowIndex - rowOffset;
originalColIndices.forEach((colIndex) => {
const strRowColIndex = `${targetRowIndex}-${colIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
} else {
// 向下复制:从操作点开始向下扩展,保持原始列数
const rowDistance = endRowIndex - operatePointRowIndex + 1;
for (let rowOffset = 0; rowOffset < rowDistance; rowOffset++) {
const targetRowIndex = operatePointRowIndex + rowOffset;
originalColIndices.forEach((colIndex) => {
const strRowColIndex = `${targetRowIndex}-${colIndex}`;
if (!moveRowColIndeKeyArr.value.includes(strRowColIndex)) {
pointMoveRowColIndeKeyArr.value.push(strRowColIndex);
}
});
}
}
}
}
};

// 鼠标抬起标记
const handleMouseUpMark = (param: CellParam) => {
const { rowIndex, colIndex } = param;
if (isEmpty(moveRowColIndeKeyArr.value)) {
moveRowColIndeKeyArr.value = [`${rowIndex}-${colIndex}`];
}
if (operatePointDragger.value) {
operatePointDragger.value = false;
}
if (!isDragging.value) {
addOperatePoint();
} else {
isDragging.value = false;
endMarkInfo.value = {
rowIndex,
colIndex,
};
addOperatePoint();
}
// 如果有移动点和框选点
if (
moveRowColIndeKeyArr.value.length > 0 &&
pointMoveRowColIndeKeyArr.value.length > 0
) {
nextTick(() => {
if (!operatePointDragDirection.value) {
operatePointDragDirection.value = "vertical";
}
mouseUpFunc && mouseUpFunc();
});
}
};

// 操作点的mousedown事件处理函数
const handleOperatePointMouseDown = (e: Event) => {
e.preventDefault();
e.stopPropagation();
operatePointDragger.value = true;
};

// 操作点抬起
const handleOperatePointMouseUp = (e: Event) => {
e.preventDefault();
e.stopPropagation();
};

// 处理双击操作点
const handleOperatePointDblClick = (e: Event) => {
e.preventDefault();
e.stopPropagation();
operatePointDragger.value = false;
// 得到最小,最大的x,最大的y
let minR = -1;
let maxR = -1;
let minC = -1;
let maxC = -1;
moveRowColIndeKeyArr.value.forEach((item) => {
const [rowIndex, colIndex] = item.split("-").map(Number);
// 说明是第一次
if (!(~minR && ~maxR && ~maxC && ~minC)) {
minR = rowIndex;
maxR = rowIndex;
maxC = colIndex;
minC = colIndex;
} else {
minR = Math.min(minR, rowIndex);
maxR = Math.max(maxR, rowIndex);
maxC = Math.max(maxC, colIndex);
minC = Math.min(minC, colIndex);
}
});
// 只有一列
if (minC === maxC) {
const tableData = getTableData();
const columns = getColumns();
const curColKey = columns[maxC]?.colKey;
let fIndex = 0;
for (let rowIndex = maxR + 1; rowIndex < tableData.length; rowIndex++) {
if (tableData[rowIndex][curColKey]) {
fIndex = rowIndex - 1;
break;
} else {
pointMoveRowColIndeKeyArr.value.push(`${rowIndex}-${maxC}`);
}
}
fIndex = tableData.length - 1;
handleMouseUpMark({
rowIndex: fIndex,
colIndex: minC,
});
}
};

// 去除操作点
const clearOperatePoint = () => {
const operatePoint = document.querySelector(`.${key}operate-point`);
if (operatePoint) {
operatePoint.addEventListener("mouseup", handleOperatePointMouseUp);
operatePoint.removeEventListener(
"mousedown",
handleOperatePointMouseDown
);
operatePoint.removeEventListener("dblclick", handleOperatePointDblClick);
operatePoint.remove();
operatePointDragger.value = false;
}
};

// 添加操作点
const addOperatePoint = () => {
clearOperatePoint();
nextTick(() => {
const operatePoint = document.createElement("div");
operatePoint.className = `${key}operate-point`;
operatePoint.style.position = "absolute";
operatePoint.style.bottom = "-2.5px";
operatePoint.style.right = "-2.5px";
operatePoint.style.width = "8px";
operatePoint.style.height = "8px";
operatePoint.style.backgroundColor =
operatePointColor || "var(--td-brand-color-5)";
operatePoint.style.cursor = "crosshair";
operatePoint.style.zIndex = "100";
const cellDom = document.querySelector(`.highlight-end-cell`);
if (cellDom) {
cellDom.appendChild(operatePoint);
// 给这个点添加doubleclick事件
operatePoint.addEventListener("dblclick", handleOperatePointDblClick);
// 给这个点添加mouseup事件,避免直接触发handleMouseUpMark事件
operatePoint.addEventListener("mouseup", handleOperatePointMouseUp);
// 给这个点添加mousedown事件
operatePoint.addEventListener("mousedown", handleOperatePointMouseDown);
}
});
};

// 点击自动聚焦
const handleClickCellToFocus = (rowIndex: number, colIndex: number) => {
nextTick(() => {
const id = `#${key}${rowIndex}-${colIndex}`;
const parentDom = document.querySelector(id);
if (parentDom) {
const inputDom = parentDom.querySelector(
".t-input__inner"
) as HTMLInputElement;
inputDom.focus();
inputDom.setSelectionRange(0, String(inputDom.value).length);
}
});
};

// 复制选区内容
const copySelectionToClipboard = () => {
const columns = getColumns();
const tableData = getTableData();
if (!moveRowColIndeKeyArr.value.length) return;
// 解析所有选中的 row/col
const cellList = moveRowColIndeKeyArr.value.map((str) => {
const [row, col] = str.split("-").map(Number);
return { row, col };
});
// 计算选区的最小/最大行列
const rows = cellList.map((c) => c.row);
const cols = cellList.map((c) => c.col);
const minRow = Math.min(...rows),
maxRow = Math.max(...rows);
const minCol = Math.min(...cols),
maxCol = Math.max(...cols);

// 构造二维数组
let result: string[][] = [];
for (let i = minRow; i <= maxRow; i++) {
let rowArr: string[] = [];
for (let j = minCol; j <= maxCol; j++) {
if (moveRowColIndeKeyArr.value.includes(`${i}-${j}`)) {
let colKey = columns[j].colKey;
rowArr.push(tableData[i][colKey]);
} else {
rowArr.push("");
}
}
result.push(rowArr);
}
// 转为 Excel 兼容的文本
const text = result.map((row) => row.join("\t")).join("\n");
if (text) {
handleCopy({
text: text.trim(),
});
} else {
NotifyPlugin.error({
title: "无内容复制",
});
}
};

// 删除选区内容
const deleteSelection = () => {
if (!onDeleteCell) return;
const columns = getColumns();
moveRowColIndeKeyArr.value.forEach((item) => {
const [rowIndex, colIndex] = item.split("-").map(Number);
let colKey = columns[colIndex]?.colKey;
if (colKey) {
onDeleteCell(rowIndex, colKey);
}
});
};

// 粘贴选区内容
const pasteClipboardToSelection = async (
onPasteCell: (rowIndex: number, colKey: string, value: string) => void,
text: string
) => {
const columns = getColumns();
if (!moveRowColIndeKeyArr.value.length) return;
if (!text) return;
const rows = text.split(/\r?\n/).map((row) => row.split("\t"));
const cellList = moveRowColIndeKeyArr.value.map((str) => {
const [row, col] = str.split("-").map(Number);
return { row, col };
});
let flatValues: string[] = [];
for (let i = 0; i < rows.length; i++)
for (let j = 0; j < rows[i].length; j++) flatValues.push(rows[i][j]);
for (let i = 0; i < cellList.length; i++) {
const { row, col } = cellList[i];
let colKey = columns[col]?.colKey;
if (colKey) {
const value = flatValues[i] ?? "";
onPasteCell(row, colKey, value.trim());
}
}
};

// 处理tab键-横向移动
const handleTabKeyEnter = () => {
if (!onTabKeyEnter) return;
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
const tableData = getTableData();
const columns = getColumns();
// 检查是否已经到达表格末尾
if (
curRowIndex === tableData.length - 1 &&
curColIndex === columns.length - 1
) {
// 已经是最后一个单元格,不进行跳转
return;
}

// 开始寻找下一个可用的单元格
let foundValidCell = false;
let maxAttempts = tableData.length * columns.length; // 防止无限循环
let attempts = 0;

while (!foundValidCell && attempts < maxAttempts) {
attempts++;

// 移动到下一个单元格
curColIndex++;

// 如果当前列超出范围,移动到下一行
if (curColIndex >= columns.length) {
curColIndex = 0; // 重置到第一列(跳过第0列)
curRowIndex++;
}

// 检查是否超出表格范围
if (curRowIndex >= tableData.length) {
// 已经超出表格范围,停止查找
break;
}

// 尝试获取单元格DOM
let id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
let dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");

// 检查单元格是否可用(存在且不是disabled)
if (dom && !domClass?.includes("disabled")) {
foundValidCell = true;
// 执行跳转
onTabKeyEnter && onTabKeyEnter();
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}

// 如果没有找到有效的单元格,可以选择不执行任何操作或给出提示
if (!foundValidCell) {
console.log("没有找到下一个可用的单元格");
}
};

// 处理上下左右键
const handleArrowKeyEnter = (key: string) => {
if (!onArrowKeyEnter) return;
// 如果是上键,往上移动,但是遇到没有dom或者dom是disabled的,则再往上移动
if (key === "ArrowUp") {
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
while (curRowIndex > 0) {
curRowIndex--;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
break;
}
}
if (curRowIndex >= 0 && dom) {
onArrowKeyEnter && onArrowKeyEnter(key);
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}
// 如果是下键,往下移动,但是遇到没有dom或者dom是disabled的,则再往下移动
else if (key === "ArrowDown") {
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
const tableData = getTableData();
while (curRowIndex < tableData.length - 1) {
curRowIndex++;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
break;
}
}
if (curRowIndex < tableData.length && dom) {
onArrowKeyEnter && onArrowKeyEnter(key);
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}
// 如果是左键,往左移动,但是遇到没有dom或者dom是disabled的,则再往左移动
else if (key === "ArrowLeft") {
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
while (curColIndex > 0) {
curColIndex--;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
break;
}
}
if (curColIndex >= 0 && dom) {
onArrowKeyEnter && onArrowKeyEnter(key);
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}
// 如果是右键,往右移动,但是遇到没有dom或者dom是disabled的,则再往右移动
else if (key === "ArrowRight") {
// 得到当前moveRowColIndeKeyArr
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
const columns = getColumns();
while (curColIndex < columns.length - 1) {
curColIndex++;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
break;
}
}
if (curColIndex < columns.length && dom) {
onArrowKeyEnter && onArrowKeyEnter(key);
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}
};

// 处理回车键
const handleEnterKeyEnter = async () => {
if (!onEnterKeyEnter) return;
// 回车键向下移动,遇到disabled或者没有dom,继续向下移动,然后到最底下的时候,把rowIndex变成0,colIndex+1,继续向下移动,当移动到最后一个单元格的时候,也就是rowIndex=tableData.length-1,colIndex=columns.length-1,停止移动,参考tab的横向移动,这里只是把这个横向改成纵向了
const curMoveRowColIndeKeyArr = moveRowColIndeKeyArr.value;
const [rowIndex, colIndex] = curMoveRowColIndeKeyArr[0].split("-");
let curColIndex = Number(colIndex);
let curRowIndex = Number(rowIndex);
let dom: HTMLElement | null = null;
const tableData = getTableData();
const columns = getColumns();
// 检查是否已经到达表格末尾
if (
curRowIndex === tableData.length - 1 &&
curColIndex === columns.length - 1
) {
// 已经是最后一个单元格,不进行跳转
return;
}
let foundValidCell = false;
let maxAttempts = tableData.length * columns.length; // 防止无限循环
let attempts = 0;
while (!foundValidCell && attempts < maxAttempts) {
attempts++;
curRowIndex++;
const id = `#${config.key}-no-edit-cell-${curRowIndex}-${curColIndex}`;
dom = document.querySelector(id) as HTMLElement;
const domClass = dom?.getAttribute("class");
if (dom && !domClass?.includes("disabled")) {
foundValidCell = true;
} else {
if (curRowIndex >= tableData.length) {
curRowIndex = -1;
curColIndex++;
}
}
}
if (foundValidCell) {
await onEnterKeyEnter();
if (dom) {
dom.click();
setMoveRowColIndeKeyArr([`${curRowIndex}-${curColIndex}`]);
dom.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
} else {
console.error("没有找到下一个可用的单元格");
}
};

// 处理键盘事件
const handleKeydown = async (e: KeyboardEvent) => {
// Ctrl+C / Cmd+C: 复制
if ((e.ctrlKey || e.metaKey) && e.key === "c") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length > 0) {
e.preventDefault();
copySelectionToClipboard();
}
}
// Backspace: 删除
else if (e.key === "Backspace") {
if (moveRowColIndeKeyArr.value && moveRowColIndeKeyArr.value.length > 1) {
e.preventDefault();
deleteSelection();
}
}
// tab键
else if (e.key === "Tab") {
if (
moveRowColIndeKeyArr.value &&
moveRowColIndeKeyArr.value.length === 1
) {
e.preventDefault();
handleTabKeyEnter();
}
}
// 上下左右键
else if (
e.key === "ArrowUp" ||
e.key === "ArrowDown" ||
e.key === "ArrowLeft" ||
e.key === "ArrowRight"
) {
if (
moveRowColIndeKeyArr.value &&
moveRowColIndeKeyArr.value.length === 1
) {
e.preventDefault();
handleArrowKeyEnter(e.key);
}
}
// 回车键
else if (e.key === "Enter") {
if (
moveRowColIndeKeyArr.value &&
moveRowColIndeKeyArr.value.length === 1
) {
e.preventDefault();
handleEnterKeyEnter();
}
}
};

// 将pointMoveRowColIndeKeyArr的点位合并,设置成moveRowColIndeKeyArr的点位,去重
const setPointMoveRowColIndeKeyArrToMoveRowColIndeKeyArr = () => {
moveRowColIndeKeyArr.value = [
...new Set([
...moveRowColIndeKeyArr.value,
...pointMoveRowColIndeKeyArr.value,
]),
];
pointMoveRowColIndeKeyArr.value = [];
addOperatePoint();
};

// 手动设置当前选区
const setMoveRowColIndeKeyArr = (pointArr: string[]) => {
clearStartAndEndMark();
moveRowColIndeKeyArr.value = [...new Set([...pointArr])];
pointMoveRowColIndeKeyArr.value = [];
addOperatePoint();
};

// 选中列
const setMoveRowColCurrentCol = (colIndex: number) => {
const tableData = getTableData();
const pointArr: string[] = [];
tableData.forEach((_, index) => {
pointArr.push(`${index}-${colIndex}`);
});
setMoveRowColIndeKeyArr(pointArr);
};

// 选中行
const setMoveRowColCurrentRow = (param: {
rowIndex: number;
filterKeys: string[];
}) => {
const { rowIndex, filterKeys } = param;
const columnData = getColumns().filter(
(item) => !filterKeys.includes(item.colKey)
);
const pointArr: string[] = [];
columnData.forEach((_, index) => {
pointArr.push(`${rowIndex}-${index}`);
});
setMoveRowColIndeKeyArr(pointArr);
};

return {
curNeedHighLightRowAndCol,
handleHighlight,
getHighlightColorClass,
handleClickCellToFocus,
addOperatePoint,
handleMouseDownMark,
handleMouseMoveMark,
handleMouseUpMark,
handleKeydown,
moveRowColIndeKeyArr,
pasteClipboardToSelection,
getNeedGiftData,
setPointMoveRowColIndeKeyArrToMoveRowColIndeKeyArr,
setMoveRowColCurrentCol,
setMoveRowColCurrentRow,
setMoveRowColIndeKeyArr,
};
}

完整效果展示

这里注意,你如果有disable的单元格,赋值的那些方法要过滤的,我给出的都死无disable的情况,这里我单独加了个disable只是为了演示跳格子我会跳过去

结语

本篇文章就到这里了,更多内容敬请期待,债见~

下一篇:
findLastIndex-浏览器兼容问题