gbxlxs 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -1
- package/src/ops.js +188 -25
- package/src/session.js +46 -29
- package/src/workbook/index.js +2 -2
- package/src/workbook/ref-shift.js +68 -2
- package/src/workbook/sheet-ops/cols.js +7 -3
- package/src/workbook/sheet-ops/index.js +1 -0
- package/src/workbook/sheet-ops/rows.js +7 -3
- package/src/workbook/sheet-ops/shared.js +97 -12
- package/src/workbook/sheet-ops/sort.js +4 -0
- package/src/workbook/validate.js +4 -1
- package/src/workbook/xlsx/content-types-writer.js +56 -209
- package/src/workbook/xlsx/reader.js +13 -7
- package/src/workbook/xlsx/roundtrip-parts.js +1 -1
- package/src/workbook/xlsx/roundtrip.js +128 -30
- package/src/workbook/xlsx/workbook-writer.js +13 -6
- package/src/workbook/xlsx/worksheet-cell.js +9 -9
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gbxlxs",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Standalone spreadsheet (XLSX) engine: read/write xlsx, workbook model ops and CSV/HTML import-export.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
"src",
|
|
18
18
|
"LICENSE"
|
|
19
19
|
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"test": "node --test test/editing.test.js test/references.test.js test/session.test.js test/roundtrip.test.js"
|
|
22
|
+
},
|
|
20
23
|
"dependencies": {
|
|
21
24
|
"gbooxml": "^0.1.0"
|
|
22
25
|
},
|
package/src/ops.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// [坑] 值必须双侧同步:读模型 rows 是稠密矩形、cells Map 是详细条目,写出时 cells 的 value 优先于 rows(worksheet-writer 的 apply overrides)——
|
|
4
4
|
// 只写 rows 而不同步 cells 条目,会把该格旧值原样写回(数据丢失级 bug)。setValue/setFormula 已封装此规则。
|
|
5
5
|
// [坑] 样式对象跨格共享:同格式格共享 font/fill/border 对象引用,修改必须整体克隆后替换(cloneCellStyle),禁原地改任何嵌套对象。
|
|
6
|
-
import { formatValue, cloneCellStyle, hideRows, parseRange, isInRange, cellRef, inferType, FORBIDDEN_SHEET_NAME_CHARS, MAX_SHEET_NAME_LENGTH } from './workbook/index.js';
|
|
6
|
+
import { formatValue, cloneCellStyle, hideRows, parseRange, isInRange, cellRef, inferType, linkWorkbookSheets, FORBIDDEN_SHEET_NAME_CHARS, MAX_SHEET_NAME_LENGTH, RESERVED_SHEET_NAME } from './workbook/index.js';
|
|
7
|
+
import { deleteSheetRefs, renameSheetRefs, translateFormulaRows } from './workbook/ref-shift.js';
|
|
7
8
|
|
|
8
9
|
/* ==================== 单元格访问 ==================== */
|
|
9
10
|
|
|
@@ -47,6 +48,16 @@ export function getStyle(sheet, r, c) {
|
|
|
47
48
|
return sheet.cells?.get(keyOf(r, c))?.style || null;
|
|
48
49
|
}
|
|
49
50
|
|
|
51
|
+
/** 公式及其类型元数据必须整体清除:只删 formula 会把 array/shared/dynamic 标记留给下一个公式 */
|
|
52
|
+
function clearFormulaMeta(entry) {
|
|
53
|
+
delete entry.formula;
|
|
54
|
+
delete entry.formulaResult;
|
|
55
|
+
delete entry.formulaType;
|
|
56
|
+
delete entry.formulaRef;
|
|
57
|
+
delete entry.formulaSharedIndex;
|
|
58
|
+
delete entry.formulaDynamic;
|
|
59
|
+
}
|
|
60
|
+
|
|
50
61
|
/** 纯值/样式格剥离为 rows 值(无附加属性即删条目,保持模型精简) */
|
|
51
62
|
function pruneEntry(sheet, r, c) {
|
|
52
63
|
if (!sheet.cells) return;
|
|
@@ -58,15 +69,15 @@ function pruneEntry(sheet, r, c) {
|
|
|
58
69
|
}
|
|
59
70
|
}
|
|
60
71
|
|
|
61
|
-
/**
|
|
72
|
+
/** 写值(同时清公式/富文本);rows 与 cells 条目双侧同步 */
|
|
62
73
|
export function setValue(sheet, r, c, value) {
|
|
63
74
|
ensureCell(sheet, r, c);
|
|
64
75
|
sheet.rows[r][c] = value;
|
|
65
76
|
const entry = sheet.cells?.get(keyOf(r, c));
|
|
66
77
|
if (entry) {
|
|
67
78
|
entry.value = value;
|
|
68
|
-
|
|
69
|
-
delete entry.
|
|
79
|
+
clearFormulaMeta(entry);
|
|
80
|
+
delete entry.richText;
|
|
70
81
|
pruneEntry(sheet, r, c);
|
|
71
82
|
}
|
|
72
83
|
}
|
|
@@ -85,15 +96,16 @@ export function setFormula(sheet, r, c, formula, result = null) {
|
|
|
85
96
|
sheet.cells.set(key, entry);
|
|
86
97
|
}
|
|
87
98
|
if (!entry) return;
|
|
99
|
+
clearFormulaMeta(entry);
|
|
88
100
|
if (!formula) {
|
|
89
|
-
delete entry.formula;
|
|
90
|
-
delete entry.formulaResult;
|
|
91
101
|
pruneEntry(sheet, r, c);
|
|
92
102
|
return;
|
|
93
103
|
}
|
|
94
104
|
entry.formula = formula;
|
|
95
105
|
entry.formulaResult = result ?? null;
|
|
96
106
|
entry.value = entry.formulaResult;
|
|
107
|
+
// [坑] 富文本在写出侧优先于公式;改公式必须清掉旧富文本,否则新公式不生效
|
|
108
|
+
delete entry.richText;
|
|
97
109
|
sheet.rows[r][c] = entry.formulaResult;
|
|
98
110
|
}
|
|
99
111
|
|
|
@@ -118,7 +130,7 @@ export function setStyle(sheet, r, c, patch) {
|
|
|
118
130
|
}
|
|
119
131
|
|
|
120
132
|
/**
|
|
121
|
-
* 单元格快照(撤销/剪贴板共用原语):style/comment/hyperlink 按不可变语义存引用(铁律保证旧对象不被原地改)。
|
|
133
|
+
* 单元格快照(撤销/剪贴板共用原语):style/comment/hyperlink/richText 按不可变语义存引用(铁律保证旧对象不被原地改)。
|
|
122
134
|
* 空内容格返回 null(无 cells 条目且无值)。
|
|
123
135
|
*/
|
|
124
136
|
export function captureCell(sheet, r, c) {
|
|
@@ -129,20 +141,26 @@ export function captureCell(sheet, r, c) {
|
|
|
129
141
|
value,
|
|
130
142
|
formula: entry?.formula ?? null,
|
|
131
143
|
formulaResult: entry?.formulaResult ?? null,
|
|
144
|
+
formulaType: entry?.formulaType ?? null,
|
|
145
|
+
formulaRef: entry?.formulaRef ?? null,
|
|
146
|
+
formulaSharedIndex: entry?.formulaSharedIndex ?? null,
|
|
147
|
+
formulaDynamic: entry?.formulaDynamic ?? null,
|
|
132
148
|
style: entry?.style ?? null,
|
|
149
|
+
richText: entry?.richText ?? null,
|
|
133
150
|
checkbox: entry?.checkbox ?? null,
|
|
134
151
|
hyperlink: entry?.hyperlink ?? null,
|
|
135
152
|
comment: entry?.comment ?? null,
|
|
136
153
|
};
|
|
137
154
|
}
|
|
138
155
|
|
|
139
|
-
/** 应用单元格快照(快照为 null =
|
|
156
|
+
/** 应用单元格快照(快照为 null = 清空为纯空格:值/公式/样式/富文本/复选框/链接/批注全清) */
|
|
140
157
|
export function applyCell(sheet, r, c, snap) {
|
|
141
158
|
if (!snap) {
|
|
142
159
|
setValue(sheet, r, c, null);
|
|
143
160
|
const entry = getEntry(sheet, r, c);
|
|
144
161
|
if (entry) {
|
|
145
162
|
delete entry.style;
|
|
163
|
+
delete entry.richText;
|
|
146
164
|
delete entry.checkbox;
|
|
147
165
|
delete entry.hyperlink;
|
|
148
166
|
delete entry.comment;
|
|
@@ -152,14 +170,14 @@ export function applyCell(sheet, r, c, snap) {
|
|
|
152
170
|
}
|
|
153
171
|
ensureCell(sheet, r, c);
|
|
154
172
|
const key = keyOf(r, c);
|
|
155
|
-
const wantsEntry = snap.formula != null || snap.style != null || Boolean(snap.checkbox) || snap.hyperlink != null || snap.comment != null;
|
|
173
|
+
const wantsEntry = snap.formula != null || snap.style != null || snap.richText != null || Boolean(snap.checkbox) || snap.hyperlink != null || snap.comment != null;
|
|
156
174
|
let entry = sheet.cells?.get(key);
|
|
157
175
|
if (!wantsEntry) {
|
|
158
176
|
if (entry) {
|
|
159
177
|
entry.value = snap.value;
|
|
160
|
-
|
|
161
|
-
delete entry.formulaResult;
|
|
178
|
+
clearFormulaMeta(entry);
|
|
162
179
|
delete entry.style;
|
|
180
|
+
delete entry.richText;
|
|
163
181
|
delete entry.checkbox;
|
|
164
182
|
delete entry.hyperlink;
|
|
165
183
|
delete entry.comment;
|
|
@@ -177,12 +195,21 @@ export function applyCell(sheet, r, c, snap) {
|
|
|
177
195
|
if (snap.formula != null) {
|
|
178
196
|
entry.formula = snap.formula;
|
|
179
197
|
entry.formulaResult = snap.formulaResult;
|
|
198
|
+
if (snap.formulaType != null) entry.formulaType = snap.formulaType;
|
|
199
|
+
else delete entry.formulaType;
|
|
200
|
+
if (snap.formulaRef != null) entry.formulaRef = snap.formulaRef;
|
|
201
|
+
else delete entry.formulaRef;
|
|
202
|
+
if (snap.formulaSharedIndex != null) entry.formulaSharedIndex = snap.formulaSharedIndex;
|
|
203
|
+
else delete entry.formulaSharedIndex;
|
|
204
|
+
if (snap.formulaDynamic) entry.formulaDynamic = true;
|
|
205
|
+
else delete entry.formulaDynamic;
|
|
180
206
|
} else {
|
|
181
|
-
|
|
182
|
-
delete entry.formulaResult;
|
|
207
|
+
clearFormulaMeta(entry);
|
|
183
208
|
}
|
|
184
209
|
if (snap.style) entry.style = snap.style;
|
|
185
210
|
else delete entry.style;
|
|
211
|
+
if (snap.richText) entry.richText = snap.richText;
|
|
212
|
+
else delete entry.richText;
|
|
186
213
|
if (snap.checkbox) entry.checkbox = true;
|
|
187
214
|
else delete entry.checkbox;
|
|
188
215
|
if (snap.hyperlink) entry.hyperlink = snap.hyperlink;
|
|
@@ -393,6 +420,7 @@ export function replaceStyle(sheet, r, c, style) {
|
|
|
393
420
|
|
|
394
421
|
/** 取消全部隐藏行/列 */
|
|
395
422
|
export function unhideAll(sheet) {
|
|
423
|
+
filterHiddenRows.delete(sheet);
|
|
396
424
|
if (sheet.rowDefs) {
|
|
397
425
|
for (const [R, def] of [...sheet.rowDefs]) {
|
|
398
426
|
delete def.hidden;
|
|
@@ -412,21 +440,115 @@ export { insertRows, deleteRows, insertColumns, deleteColumns, hideRows, hideCol
|
|
|
412
440
|
/* ==================== 工作表操作 ==================== */
|
|
413
441
|
|
|
414
442
|
function uniqueSheetName(workbook, base) {
|
|
415
|
-
|
|
443
|
+
// [坑] Excel 按大小写不敏感判重:'Sheet' 与 'sheet' 同名,去重也必须转小写比较
|
|
444
|
+
const names = new Set(workbook.sheets.map((s) => String(s.name).toLowerCase()));
|
|
416
445
|
const root = String(base || 'Sheet').trim() || 'Sheet';
|
|
417
|
-
if (!names.has(root)) return root;
|
|
446
|
+
if (!names.has(root.toLowerCase())) return root;
|
|
418
447
|
for (let i = 2; ; i++) {
|
|
419
448
|
const n = `${root}${i}`;
|
|
420
|
-
if (!names.has(n)) return n;
|
|
449
|
+
if (!names.has(n.toLowerCase())) return n;
|
|
421
450
|
}
|
|
422
451
|
}
|
|
423
452
|
|
|
424
453
|
export function addSheet(workbook, name) {
|
|
425
454
|
workbook.sheets.push({ name: uniqueSheetName(workbook, name), rows: [[]] });
|
|
455
|
+
linkWorkbookSheets(workbook);
|
|
426
456
|
return workbook.sheets.length - 1;
|
|
427
457
|
}
|
|
428
458
|
|
|
459
|
+
const CHART_REF_FIELDS = ['valuesRef', 'categoriesRef', 'bubbleSizeRef'];
|
|
460
|
+
|
|
461
|
+
/** 遍历工作表里所有可能含跨表引用的文本(公式/校验/条件格式/迷你图/图表序列) */
|
|
462
|
+
function forEachFormulaRef(sheet, rewrite) {
|
|
463
|
+
if (sheet.cells) {
|
|
464
|
+
for (const cell of sheet.cells.values()) {
|
|
465
|
+
if (cell.formula) cell.formula = rewrite(cell.formula);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
if (sheet.dataValidations) {
|
|
469
|
+
for (const dv of sheet.dataValidations) {
|
|
470
|
+
if (dv.formula1) dv.formula1 = rewrite(dv.formula1);
|
|
471
|
+
if (dv.formula2) dv.formula2 = rewrite(dv.formula2);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (sheet.conditionalRules) {
|
|
475
|
+
for (const rule of sheet.conditionalRules) {
|
|
476
|
+
if (Array.isArray(rule.formula)) rule.formula = rule.formula.map(rewrite);
|
|
477
|
+
else if (typeof rule.formula === 'string') rule.formula = rewrite(rule.formula);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (sheet.sparklines) {
|
|
481
|
+
for (const sparkline of sheet.sparklines) {
|
|
482
|
+
if (sparkline.dataRange) sparkline.dataRange = rewrite(sparkline.dataRange);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
if (sheet.charts) {
|
|
486
|
+
for (const chart of sheet.charts) {
|
|
487
|
+
if (!chart.series) continue;
|
|
488
|
+
for (const series of chart.series) {
|
|
489
|
+
for (const key of CHART_REF_FIELDS) {
|
|
490
|
+
if (typeof series[key] === 'string') series[key] = rewrite(series[key]);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function renameWorkbookSheetReferences(workbook, oldName, newName) {
|
|
498
|
+
const rewrite = (formula) => renameSheetRefs(formula, oldName, newName);
|
|
499
|
+
const target = String(oldName).toLowerCase();
|
|
500
|
+
for (const sheet of workbook.sheets) forEachFormulaRef(sheet, rewrite);
|
|
501
|
+
if (workbook.namedRanges) {
|
|
502
|
+
for (const named of workbook.namedRanges) {
|
|
503
|
+
if (named.range) named.range = rewrite(named.range);
|
|
504
|
+
if (named.scope !== void 0 && String(named.scope).toLowerCase() === target) named.scope = newName;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
if (workbook.pivotCaches) {
|
|
508
|
+
for (const cache of workbook.pivotCaches) {
|
|
509
|
+
if (typeof cache.sourceSheet === 'string' && cache.sourceSheet.toLowerCase() === target) cache.sourceSheet = newName;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
for (const sheet of workbook.sheets) {
|
|
513
|
+
if (!sheet.pivotTables) continue;
|
|
514
|
+
for (const pivot of sheet.pivotTables) {
|
|
515
|
+
if (typeof pivot.sourceSheet === 'string' && pivot.sourceSheet.toLowerCase() === target) pivot.sourceSheet = newName;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function dropWorkbookSheetReferences(workbook, removedName) {
|
|
521
|
+
const target = String(removedName).toLowerCase();
|
|
522
|
+
const rewrite = (formula) => deleteSheetRefs(formula, removedName);
|
|
523
|
+
for (const sheet of workbook.sheets) {
|
|
524
|
+
forEachFormulaRef(sheet, rewrite);
|
|
525
|
+
if (sheet.pivotTables) {
|
|
526
|
+
sheet.pivotTables = sheet.pivotTables.filter(
|
|
527
|
+
(pivot) => !(typeof pivot.sourceSheet === 'string' && pivot.sourceSheet.toLowerCase() === target),
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
if (workbook.namedRanges) {
|
|
532
|
+
workbook.namedRanges = workbook.namedRanges.filter(
|
|
533
|
+
(named) => !(named.scope !== void 0 && String(named.scope).toLowerCase() === target),
|
|
534
|
+
);
|
|
535
|
+
for (const named of workbook.namedRanges) {
|
|
536
|
+
if (named.range) named.range = rewrite(named.range);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
if (workbook.pivotCaches) {
|
|
540
|
+
workbook.pivotCaches = workbook.pivotCaches.filter(
|
|
541
|
+
(cache) => !(typeof cache.sourceSheet === 'string' && cache.sourceSheet.toLowerCase() === target),
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
429
546
|
export function removeSheetAt(workbook, index) {
|
|
547
|
+
// Excel 要求工作簿至少保留一张可见工作表,删到 0 张会产出无法打开的文件
|
|
548
|
+
if (workbook.sheets.length <= 1) throw new Error('工作簿至少需要保留一张工作表');
|
|
549
|
+
const removed = workbook.sheets[index];
|
|
550
|
+
if (!removed) return;
|
|
551
|
+
if (removed.name) dropWorkbookSheetReferences(workbook, removed.name);
|
|
430
552
|
workbook.sheets.splice(index, 1);
|
|
431
553
|
const active = workbook.activeSheet ?? 0;
|
|
432
554
|
if (active > 0 && active >= index) workbook.activeSheet = active - 1;
|
|
@@ -438,9 +560,13 @@ export function renameSheetAt(workbook, index, name) {
|
|
|
438
560
|
if (!trimmed) throw new Error('工作表名不能为空');
|
|
439
561
|
if (trimmed.length > MAX_SHEET_NAME_LENGTH) throw new Error(`工作表名不能超过 ${MAX_SHEET_NAME_LENGTH} 个字符`);
|
|
440
562
|
if (FORBIDDEN_SHEET_NAME_CHARS.test(trimmed)) throw new Error('工作表名不能包含 \\ / ? * [ ] : 字符');
|
|
563
|
+
if (trimmed.startsWith("'") || trimmed.endsWith("'")) throw new Error('工作表名不能以单引号开头或结尾');
|
|
564
|
+
if (trimmed.toLowerCase() === RESERVED_SHEET_NAME) throw new Error('工作表名不能使用 Excel 保留名 "History"');
|
|
441
565
|
// [坑] Excel 按大小写不敏感判重:'Sheet' 与 'sheet' 视为同名
|
|
442
566
|
const lower = trimmed.toLowerCase();
|
|
443
567
|
if (workbook.sheets.some((s, i) => i !== index && String(s.name).toLowerCase() === lower)) throw new Error('已存在同名工作表');
|
|
568
|
+
const oldName = workbook.sheets[index].name;
|
|
569
|
+
if (oldName !== trimmed) renameWorkbookSheetReferences(workbook, oldName, trimmed);
|
|
444
570
|
workbook.sheets[index].name = trimmed;
|
|
445
571
|
}
|
|
446
572
|
|
|
@@ -587,7 +713,12 @@ export function sortRegion(sheet, region, colIndex, desc = false) {
|
|
|
587
713
|
const list = cellsByRow.get(item.src);
|
|
588
714
|
if (list) {
|
|
589
715
|
if (!sheet.cells) sheet.cells = new Map();
|
|
590
|
-
|
|
716
|
+
// [设计] 公式随行搬动时,相对行引用按移动距离平移(与 Excel 排序一致),绝对行保持不变
|
|
717
|
+
const delta = target - item.src;
|
|
718
|
+
for (const [cs, cell] of list) {
|
|
719
|
+
if (delta !== 0 && cell.formula) cell.formula = translateFormulaRows(cell.formula, delta);
|
|
720
|
+
sheet.cells.set(`${target},${cs}`, cell);
|
|
721
|
+
}
|
|
591
722
|
}
|
|
592
723
|
const def = defsByRow.get(item.src);
|
|
593
724
|
if (def !== undefined) {
|
|
@@ -624,17 +755,34 @@ export function toggleFilter(sheet, region) {
|
|
|
624
755
|
return true;
|
|
625
756
|
}
|
|
626
757
|
|
|
758
|
+
// sheet -> 当前由筛选隐藏的行。与手动隐藏分开记账,取消筛选/恢复可见时不能把用户手动隐藏的行放出来。
|
|
759
|
+
const filterHiddenRows = new WeakMap();
|
|
760
|
+
|
|
627
761
|
export function clearFilter(sheet) {
|
|
628
762
|
if (!sheet.autoFilter) return false;
|
|
629
|
-
sheet.autoFilter
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
763
|
+
const af = sheet.autoFilter;
|
|
764
|
+
const reg = parseRange(af.range);
|
|
765
|
+
const tracked = filterHiddenRows.get(sheet);
|
|
766
|
+
const toRestore = tracked ?? new Set();
|
|
767
|
+
if (!tracked && af.columns) {
|
|
768
|
+
// 从文件导入的筛选没有内存标记:把“隐藏且不满足现有条件”的行视为筛选隐藏
|
|
769
|
+
for (let R = reg.startRow + 1; R <= reg.endRow; R++) {
|
|
770
|
+
if (!sheet.rowDefs?.get(R)?.hidden) continue;
|
|
771
|
+
const visible = af.columns.every((cond) =>
|
|
772
|
+
cond.filters.includes(getDisplayText(sheet, R, reg.startCol + cond.colIndex)),
|
|
773
|
+
);
|
|
774
|
+
if (!visible) toRestore.add(R);
|
|
635
775
|
}
|
|
636
|
-
if (sheet.rowDefs.size === 0) sheet.rowDefs = undefined;
|
|
637
776
|
}
|
|
777
|
+
for (const R of toRestore) {
|
|
778
|
+
const def = sheet.rowDefs?.get(R);
|
|
779
|
+
if (!def) continue;
|
|
780
|
+
delete def.hidden;
|
|
781
|
+
if (Object.keys(def).length === 0) sheet.rowDefs.delete(R);
|
|
782
|
+
}
|
|
783
|
+
filterHiddenRows.delete(sheet);
|
|
784
|
+
sheet.autoFilter = undefined;
|
|
785
|
+
if (sheet.rowDefs && sheet.rowDefs.size === 0) sheet.rowDefs = undefined;
|
|
638
786
|
return true;
|
|
639
787
|
}
|
|
640
788
|
|
|
@@ -658,6 +806,19 @@ export function applyFilter(sheet, sheetCol, values) {
|
|
|
658
806
|
const reg = parseRange(af.range);
|
|
659
807
|
const relCol = sheetCol - reg.startCol;
|
|
660
808
|
if (relCol < 0 || sheetCol > reg.endCol) return;
|
|
809
|
+
let tracked = filterHiddenRows.get(sheet);
|
|
810
|
+
if (!tracked) {
|
|
811
|
+
tracked = new Set();
|
|
812
|
+
// 首次应用(可能来自文件导入):先按旧条件认领筛选隐藏行,避免把手动隐藏行算进来
|
|
813
|
+
for (let R = reg.startRow + 1; R <= reg.endRow; R++) {
|
|
814
|
+
if (!sheet.rowDefs?.get(R)?.hidden) continue;
|
|
815
|
+
const visible = (af.columns || []).every((cond) =>
|
|
816
|
+
cond.filters.includes(getDisplayText(sheet, R, reg.startCol + cond.colIndex)),
|
|
817
|
+
);
|
|
818
|
+
if (!visible) tracked.add(R);
|
|
819
|
+
}
|
|
820
|
+
filterHiddenRows.set(sheet, tracked);
|
|
821
|
+
}
|
|
661
822
|
const cols = (af.columns || []).filter((entry) => entry.colIndex !== relCol);
|
|
662
823
|
if (values !== null && values !== undefined) cols.push({ colIndex: relCol, filters: values.map(String) });
|
|
663
824
|
af.columns = cols.length ? cols : undefined;
|
|
@@ -667,12 +828,14 @@ export function applyFilter(sheet, sheetCol, values) {
|
|
|
667
828
|
);
|
|
668
829
|
const def = sheet.rowDefs?.get(R);
|
|
669
830
|
if (visible) {
|
|
670
|
-
|
|
831
|
+
// 只恢复本筛选手动隐藏的行;原本就手动隐藏的行保持隐藏
|
|
832
|
+
if (tracked.delete(R) && def) {
|
|
671
833
|
delete def.hidden;
|
|
672
834
|
if (Object.keys(def).length === 0) sheet.rowDefs.delete(R);
|
|
673
835
|
}
|
|
674
836
|
} else if (!def?.hidden) {
|
|
675
837
|
hideRows(sheet, R, 1, true);
|
|
838
|
+
tracked.add(R);
|
|
676
839
|
}
|
|
677
840
|
}
|
|
678
841
|
if (sheet.rowDefs && sheet.rowDefs.size === 0) sheet.rowDefs = undefined;
|
package/src/session.js
CHANGED
|
@@ -20,52 +20,61 @@ export function createSheetSession({ onChange, onSerializeFailed } = {}) {
|
|
|
20
20
|
let savedRevision = 0;
|
|
21
21
|
let latestBytes = null;
|
|
22
22
|
let serializedRevision = 0;
|
|
23
|
-
let
|
|
24
|
-
|
|
23
|
+
let serializePromise = null;
|
|
24
|
+
// 每次 open/createBlank 递增:旧文件在途序列化完成后据此丢弃结果,不能写进新会话
|
|
25
|
+
let generation = 0;
|
|
25
26
|
let serializeError = null;
|
|
27
|
+
// 最近一次交给上传方的字节对应的 revision(serializeNow/getLatestBytes 时记录),ack 只认这个值
|
|
28
|
+
let handoffRevision = 0;
|
|
29
|
+
|
|
30
|
+
const reset = () => {
|
|
31
|
+
generation += 1;
|
|
32
|
+
revision = 0;
|
|
33
|
+
savedRevision = 0;
|
|
34
|
+
serializedRevision = 0;
|
|
35
|
+
serializePromise = null;
|
|
36
|
+
serializeError = null;
|
|
37
|
+
handoffRevision = 0;
|
|
38
|
+
};
|
|
26
39
|
|
|
27
40
|
/** 单飞异步序列化:本轮完成后若 revision 又涨立即再跑一轮,直到追上最新(失败停在旧字节,下次 markChanged/取字节时重试) */
|
|
28
41
|
const kickSerialize = () => {
|
|
29
|
-
if (
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
42
|
+
if (!workbook) return Promise.resolve();
|
|
43
|
+
if (serializePromise) return serializePromise;
|
|
44
|
+
const gen = generation;
|
|
45
|
+
const wb = workbook;
|
|
46
|
+
serializePromise = (async () => {
|
|
33
47
|
try {
|
|
34
48
|
for (;;) {
|
|
49
|
+
if (gen !== generation) return;
|
|
35
50
|
const rev = revision;
|
|
36
|
-
const bytes = await saveXlsx(
|
|
51
|
+
const bytes = await saveXlsx(wb);
|
|
52
|
+
if (gen !== generation) return;
|
|
37
53
|
latestBytes = bytes;
|
|
38
54
|
serializedRevision = rev;
|
|
39
55
|
if (serializeError) {
|
|
40
56
|
serializeError = null;
|
|
41
|
-
serializeFailed = false;
|
|
42
57
|
onSerializeFailed?.(null);
|
|
43
58
|
}
|
|
44
59
|
if (revision === rev) break;
|
|
45
60
|
}
|
|
46
61
|
} catch (err) {
|
|
62
|
+
if (gen !== generation) return;
|
|
47
63
|
console.error('[sheetSession] 序列化失败', err);
|
|
48
|
-
serializeFailed = true;
|
|
49
64
|
serializeError = err instanceof Error ? err : new Error(String(err));
|
|
50
65
|
onSerializeFailed?.(serializeError);
|
|
51
66
|
} finally {
|
|
52
|
-
|
|
67
|
+
if (gen === generation) serializePromise = null;
|
|
53
68
|
}
|
|
54
69
|
})();
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const reset = () => {
|
|
58
|
-
revision = 0;
|
|
59
|
-
savedRevision = 0;
|
|
60
|
-
serializedRevision = 0;
|
|
61
|
-
serializing = false;
|
|
62
|
-
serializeFailed = false;
|
|
63
|
-
serializeError = null;
|
|
70
|
+
return serializePromise;
|
|
64
71
|
};
|
|
65
72
|
|
|
66
73
|
/** 打开磁盘字节:0 字节 = 空稿(首次保存才写出真 xlsx);非法内容抛可读错误、拒绝静默清空 */
|
|
67
74
|
const open = async (bytes) => {
|
|
75
|
+
reset();
|
|
68
76
|
workbook = null;
|
|
77
|
+
latestBytes = null;
|
|
69
78
|
if (!bytes || bytes.byteLength === 0) {
|
|
70
79
|
await createBlank();
|
|
71
80
|
return;
|
|
@@ -84,6 +93,9 @@ export function createSheetSession({ onChange, onSerializeFailed } = {}) {
|
|
|
84
93
|
};
|
|
85
94
|
|
|
86
95
|
const createBlank = async () => {
|
|
96
|
+
reset();
|
|
97
|
+
workbook = null;
|
|
98
|
+
latestBytes = null;
|
|
87
99
|
const bytes = await blankBytes();
|
|
88
100
|
workbook = await openXlsx(bytes, { readStyles: true });
|
|
89
101
|
latestBytes = bytes;
|
|
@@ -96,20 +108,21 @@ export function createSheetSession({ onChange, onSerializeFailed } = {}) {
|
|
|
96
108
|
onChange?.();
|
|
97
109
|
};
|
|
98
110
|
|
|
99
|
-
/**
|
|
100
|
-
|
|
101
|
-
|
|
111
|
+
/**
|
|
112
|
+
* 异步提交成功后的回执。默认认「最近一次交接给上传方的 revision」,不会把后序列化出的新版误标为已保存;
|
|
113
|
+
* 调用方若自行保存了 revision,也可显式传入。
|
|
114
|
+
*/
|
|
115
|
+
const ackFlushed = (rev = handoffRevision) => {
|
|
116
|
+
const acked = Number.isInteger(rev) ? Math.min(rev, serializedRevision) : handoffRevision;
|
|
117
|
+
if (acked > savedRevision) savedRevision = acked;
|
|
102
118
|
};
|
|
103
119
|
|
|
104
120
|
const isSerialized = () => serializedRevision >= revision;
|
|
105
121
|
|
|
106
122
|
/** 等待序列化追上当前 revision(手动保存/另存为/下载前调用),返回最新字节;失败不空转(返回旧字节) */
|
|
107
123
|
const serializeNow = async () => {
|
|
108
|
-
kickSerialize();
|
|
109
|
-
|
|
110
|
-
await new Promise((resolve) => setTimeout(resolve, 15));
|
|
111
|
-
kickSerialize();
|
|
112
|
-
}
|
|
124
|
+
await kickSerialize();
|
|
125
|
+
handoffRevision = serializedRevision;
|
|
113
126
|
return latestBytes;
|
|
114
127
|
};
|
|
115
128
|
|
|
@@ -140,9 +153,13 @@ export function createSheetSession({ onChange, onSerializeFailed } = {}) {
|
|
|
140
153
|
isDirty: () => revision > savedRevision,
|
|
141
154
|
/** 当前是否处于序列化失败态(失败给错误、健康给 null):调用方据此决定清不清错误文案 */
|
|
142
155
|
getSerializeError: () => serializeError,
|
|
143
|
-
/** 序列化是否已追上当前 revision(关闭闸门据此判断 unmount flushSync
|
|
144
|
-
getLatestBytes: () =>
|
|
156
|
+
/** 序列化是否已追上当前 revision(关闭闸门据此判断 unmount flushSync 送不送得出最新字节);调用即记录一次字节交接 */
|
|
157
|
+
getLatestBytes: () => {
|
|
158
|
+
handoffRevision = serializedRevision;
|
|
159
|
+
return latestBytes;
|
|
160
|
+
},
|
|
145
161
|
isSerialized,
|
|
146
162
|
getRevision: () => revision,
|
|
163
|
+
getSerializedRevision: () => serializedRevision,
|
|
147
164
|
};
|
|
148
165
|
}
|
package/src/workbook/index.js
CHANGED
|
@@ -5,7 +5,7 @@ export { writeCsv } from "./csv/index.js";
|
|
|
5
5
|
export { formatValue } from "./number-format.js";
|
|
6
6
|
export { inferType } from "./type-infer.js";
|
|
7
7
|
export { cloneCellStyle } from "./style-clone.js";
|
|
8
|
-
export { FORBIDDEN_SHEET_NAME_CHARS, MAX_SHEET_NAME_LENGTH } from "./validate.js";
|
|
9
|
-
export { insertRows, deleteRows, insertColumns, deleteColumns, hideRows, hideColumns } from "./sheet-ops/index.js";
|
|
8
|
+
export { FORBIDDEN_SHEET_NAME_CHARS, MAX_SHEET_NAME_LENGTH, RESERVED_SHEET_NAME } from "./validate.js";
|
|
9
|
+
export { insertRows, deleteRows, insertColumns, deleteColumns, hideRows, hideColumns, linkWorkbookSheets } from "./sheet-ops/index.js";
|
|
10
10
|
export { parseCellRef, colToLetter, cellRef, letterToCol, parseRange, isInRange, replaceA1Refs } from "./cell-utils.js";
|
|
11
11
|
export { fromHtml } from "./export/index.js";
|
|
@@ -47,7 +47,10 @@ function unquoteSheet(name) {
|
|
|
47
47
|
return name.length >= 2 && name.startsWith("'") && name.endsWith("'") ? name.slice(1, -1).replace(/''/g, "'") : name;
|
|
48
48
|
}
|
|
49
49
|
function shiftMatch(match, shift) {
|
|
50
|
-
|
|
50
|
+
// qualifiedOnly:只动显式带表名前缀的引用(更新其他工作表的跨表引用时,不能碰它们本地的无前缀引用)
|
|
51
|
+
if (shift.qualifiedOnly && match.sheet1 === void 0) return rebuild(match);
|
|
52
|
+
// Excel 表名大小写不敏感:`sheet1!A1` 与 `Sheet1!A1` 指向同一张表,都要平移
|
|
53
|
+
if (match.sheet1 !== void 0 && unquoteSheet(match.sheet1).toLowerCase() !== String(shift.sheetName ?? "").toLowerCase()) {
|
|
51
54
|
return rebuild(match);
|
|
52
55
|
}
|
|
53
56
|
const start = parseRef(match.ref1);
|
|
@@ -85,7 +88,70 @@ function shiftRangeRef(range, shift) {
|
|
|
85
88
|
const shifted = shiftFormula(range, shift);
|
|
86
89
|
return shifted.includes(REF_ERROR) ? void 0 : shifted;
|
|
87
90
|
}
|
|
91
|
+
function translateRow(ref, delta) {
|
|
92
|
+
if (ref.rowAbs) return ref;
|
|
93
|
+
const row = ref.row + delta;
|
|
94
|
+
if (row < 0 || row > MAX_ROW_INDEX) return null;
|
|
95
|
+
return { ...ref, row };
|
|
96
|
+
}
|
|
97
|
+
function translateMatch(match, delta) {
|
|
98
|
+
const start = parseRef(match.ref1);
|
|
99
|
+
if (!start) return rebuild(match);
|
|
100
|
+
const movedStart = translateRow(start, delta);
|
|
101
|
+
if (match.ref2 === void 0) {
|
|
102
|
+
return movedStart === null ? REF_ERROR : `${qualifierOf(match)}${formatRef(movedStart)}`;
|
|
103
|
+
}
|
|
104
|
+
const end = parseRef(match.ref2);
|
|
105
|
+
if (!end) return rebuild(match);
|
|
106
|
+
const movedEnd = translateRow(end, delta);
|
|
107
|
+
if (movedStart === null || movedEnd === null) return REF_ERROR;
|
|
108
|
+
const tail = match.sheet2 === void 0 ? formatRef(movedEnd) : `${match.sheet2}!${formatRef(movedEnd)}`;
|
|
109
|
+
return `${qualifierOf(match)}${formatRef(movedStart)}:${tail}`;
|
|
110
|
+
}
|
|
111
|
+
/** 公式所在行移动 delta 行时,平移其相对行引用(绝对行不变);用于排序等“公式随行搬家”场景 */
|
|
112
|
+
function translateFormulaRows(formula, delta) {
|
|
113
|
+
if (delta === 0) return formula;
|
|
114
|
+
return replaceA1Ranges(formula, (match) => translateMatch(match, delta));
|
|
115
|
+
}
|
|
116
|
+
function quoteSheetName(name) {
|
|
117
|
+
const text = String(name);
|
|
118
|
+
if (/^[A-Za-z_][A-Za-z0-9_.]*$/.test(text) && !/^[A-Za-z]{1,3}\d+$/i.test(text)) return text;
|
|
119
|
+
return `'${text.replace(/'/g, "''")}'`;
|
|
120
|
+
}
|
|
121
|
+
// 排除外部引用([Book]Sheet!A1)与更长标识符中的片段
|
|
122
|
+
const QUALIFIED_PREFIX = /(?<![A-Za-z0-9_.\]])(?:\$?)(?:'((?:[^']|'')+)'|([A-Za-z_][A-Za-z0-9_.]*))!/g;
|
|
123
|
+
const QUALIFIED_TOKEN = /(?<![A-Za-z0-9_.\]])(?:\$?)(?:'((?:[^']|'')+)'|([A-Za-z_][A-Za-z0-9_.]*))!((?:\$?[A-Za-z]{1,3}\$?\d+)(?::\$?[A-Za-z]{1,3}\$?\d+)?|[A-Za-z_][A-Za-z0-9_.]*)/g;
|
|
124
|
+
function mapFormulaCode(formula, fn) {
|
|
125
|
+
const parts = String(formula).split(/("(?:[^"]|"")*")/);
|
|
126
|
+
for (let i = 0; i < parts.length; i += 2) parts[i] = fn(parts[i]);
|
|
127
|
+
return parts.join("");
|
|
128
|
+
}
|
|
129
|
+
function qualifierName(quoted, plain) {
|
|
130
|
+
return quoted !== void 0 ? quoted.replace(/''/g, "'") : plain;
|
|
131
|
+
}
|
|
132
|
+
/** 重命名工作表后,把公式/定义名称/图表引用中的表名前缀改为新名 */
|
|
133
|
+
function renameSheetRefs(formula, oldName, newName) {
|
|
134
|
+
const target = String(oldName).toLowerCase();
|
|
135
|
+
return mapFormulaCode(formula, (text) => text.replace(QUALIFIED_PREFIX, (m, quoted, plain) =>
|
|
136
|
+
qualifierName(quoted, plain).toLowerCase() === target ? `${quoteSheetName(newName)}!` : m
|
|
137
|
+
));
|
|
138
|
+
}
|
|
139
|
+
/** 删除工作表后,把指向它的限定引用整体替换为 #REF! */
|
|
140
|
+
function deleteSheetRefs(formula, removedName) {
|
|
141
|
+
const target = String(removedName).toLowerCase();
|
|
142
|
+
const replaced = mapFormulaCode(formula, (text) => text.replace(QUALIFIED_TOKEN, (m, quoted, plain) =>
|
|
143
|
+
qualifierName(quoted, plain).toLowerCase() === target ? REF_ERROR : m
|
|
144
|
+
));
|
|
145
|
+
// 区域只有一端失效时,Excel 也把整个区域显示为 #REF!
|
|
146
|
+
return replaced
|
|
147
|
+
.replace(/#REF!:#REF!/g, REF_ERROR)
|
|
148
|
+
.replace(/#REF!:(?:[A-Za-z0-9_$.]+!)?\$?[A-Za-z]{1,3}\$?\d+(?::\$?[A-Za-z]{1,3}\$?\d+)?/g, REF_ERROR)
|
|
149
|
+
.replace(/(?:[A-Za-z0-9_$.]+!)?\$?[A-Za-z]{1,3}\$?\d+:#REF!/g, REF_ERROR);
|
|
150
|
+
}
|
|
88
151
|
export {
|
|
152
|
+
deleteSheetRefs,
|
|
153
|
+
renameSheetRefs,
|
|
89
154
|
shiftFormula,
|
|
90
|
-
shiftRangeRef
|
|
155
|
+
shiftRangeRef,
|
|
156
|
+
translateFormulaRows
|
|
91
157
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// [文件] gbxlxs·列结构操作——插列/删列/隐藏列
|
|
2
2
|
|
|
3
3
|
import { parseRange } from "../cell-utils.js";
|
|
4
|
-
import { makeEmptyRow, shiftDeletedRangeCols, shiftRangeCols, shiftReferences } from "./shared.js";
|
|
4
|
+
import { makeEmptyRow, shiftDeletedRangeCols, shiftRangeCols, shiftReferences, shiftSiblingReferences } from "./shared.js";
|
|
5
5
|
|
|
6
6
|
export function insertColumns(sheet, colIndex, count) {
|
|
7
7
|
if (count <= 0) return;
|
|
@@ -70,7 +70,9 @@ export function insertColumns(sheet, colIndex, count) {
|
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
|
-
|
|
73
|
+
const shift = { axis: "col", at: colIndex, delta: count };
|
|
74
|
+
shiftReferences(sheet, shift);
|
|
75
|
+
shiftSiblingReferences(sheet, shift);
|
|
74
76
|
}
|
|
75
77
|
export function deleteColumns(sheet, colIndex, count) {
|
|
76
78
|
if (count <= 0) return;
|
|
@@ -180,7 +182,9 @@ export function deleteColumns(sheet, colIndex, count) {
|
|
|
180
182
|
}
|
|
181
183
|
}
|
|
182
184
|
}
|
|
183
|
-
|
|
185
|
+
const shift = { axis: "col", at: colIndex, delta: -count };
|
|
186
|
+
shiftReferences(sheet, shift);
|
|
187
|
+
shiftSiblingReferences(sheet, shift);
|
|
184
188
|
}
|
|
185
189
|
export function hideColumns(sheet, startCol, count, hidden = true) {
|
|
186
190
|
if (!sheet.columns) sheet.columns = [];
|
|
@@ -2,5 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
export { insertRows, deleteRows, hideRows } from "./rows.js";
|
|
4
4
|
export { insertColumns, deleteColumns, hideColumns } from "./cols.js";
|
|
5
|
+
export { linkWorkbookSheets } from "./shared.js";
|
|
5
6
|
export { cloneSheet, removeSheet } from "./sheets.js";
|
|
6
7
|
export { sortRows } from "./sort.js";
|