gbxlxs 0.1.2 → 0.1.6

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.
Files changed (120) hide show
  1. package/README.md +154 -10
  2. package/package.json +14 -6
  3. package/src/find-replace.js +251 -0
  4. package/src/index.js +11 -0
  5. package/src/ops/cells.js +218 -0
  6. package/src/ops/entry.js +43 -0
  7. package/src/ops/filter.js +260 -0
  8. package/src/ops/numfmt.js +36 -0
  9. package/src/ops/region.js +98 -0
  10. package/src/ops/sheet.js +146 -0
  11. package/src/ops/sort.js +138 -0
  12. package/src/ops/styles.js +62 -0
  13. package/src/ops/visibility.js +20 -0
  14. package/src/ops.js +71 -845
  15. package/src/print.js +284 -0
  16. package/src/session.js +3 -1
  17. package/src/threaded-comments.js +86 -0
  18. package/src/workbook/cell-utils.js +5 -3
  19. package/src/workbook/date.js +4 -0
  20. package/src/workbook/export/html.js +4 -4
  21. package/src/workbook/formula/engine.js +819 -0
  22. package/src/workbook/formula/functions/common.js +114 -0
  23. package/src/workbook/formula/functions/database.js +172 -0
  24. package/src/workbook/formula/functions/date.js +364 -0
  25. package/src/workbook/formula/functions/engineering.js +188 -0
  26. package/src/workbook/formula/functions/financial.js +307 -0
  27. package/src/workbook/formula/functions/index.js +29 -0
  28. package/src/workbook/formula/functions/information.js +162 -0
  29. package/src/workbook/formula/functions/logical.js +69 -0
  30. package/src/workbook/formula/functions/lookup.js +354 -0
  31. package/src/workbook/formula/functions/math.js +404 -0
  32. package/src/workbook/formula/functions/statistical.js +382 -0
  33. package/src/workbook/formula/functions/text.js +275 -0
  34. package/src/workbook/formula/index.js +5 -0
  35. package/src/workbook/formula/parser.js +327 -0
  36. package/src/workbook/formula/table-ref.js +136 -0
  37. package/src/workbook/formula/tokenizer.js +203 -0
  38. package/src/workbook/formula/values.js +295 -0
  39. package/src/workbook/index.js +2 -0
  40. package/src/workbook/inline-cells.js +15 -1
  41. package/src/workbook/input.js +15 -2
  42. package/src/workbook/ref-shift.js +32 -0
  43. package/src/workbook/shared-formula.js +85 -0
  44. package/src/workbook/sheet-ops/cols.js +4 -1
  45. package/src/workbook/sheet-ops/rows.js +6 -1
  46. package/src/workbook/sheet-ops/shared.js +20 -4
  47. package/src/workbook/sheet-ops/sheets.js +3 -0
  48. package/src/workbook/style-clone.js +17 -3
  49. package/src/workbook/xlsx/doc-props-writer.js +7 -1
  50. package/src/workbook/xlsx/drawing-parse.js +131 -2
  51. package/src/workbook/xlsx/drawing-writer.js +96 -82
  52. package/src/workbook/xlsx/reader.js +14 -11
  53. package/src/workbook/xlsx/roundtrip-parts.js +69 -125
  54. package/src/workbook/xlsx/roundtrip.js +93 -190
  55. package/src/workbook/xlsx/styles-writer.js +21 -13
  56. package/src/workbook/xlsx/table-export.js +162 -0
  57. package/src/workbook/xlsx/table-writer.js +3 -1
  58. package/src/workbook/xlsx/threaded-comments-writer.js +41 -0
  59. package/src/workbook/xlsx/workbook-writer.js +9 -4
  60. package/src/workbook/xlsx/worksheet-cell.js +3 -0
  61. package/src/workbook/xlsx/worksheet-handler-close.js +33 -6
  62. package/src/workbook/xlsx/worksheet-handler-open.js +30 -0
  63. package/src/workbook/xlsx/worksheet-parser-state.js +7 -2
  64. package/src/workbook/xlsx/worksheet-writer.js +74 -45
  65. package/src/workbook/xlsx/writer.js +4 -2
  66. package/web/app/core/clipboard.js +240 -0
  67. package/web/app/core/cmd-comment.js +35 -0
  68. package/web/app/core/cmd-core.js +181 -0
  69. package/web/app/core/cmd-data.js +167 -0
  70. package/web/app/core/cmd-edit.js +229 -0
  71. package/web/app/core/cmd-filter.js +172 -0
  72. package/web/app/core/cmd-find.js +74 -0
  73. package/web/app/core/cmd-format.js +65 -0
  74. package/web/app/core/cmd-shape.js +90 -0
  75. package/web/app/core/cmd-structure.js +190 -0
  76. package/web/app/core/commands.js +23 -0
  77. package/web/app/core/geometry.js +112 -0
  78. package/web/app/core/history.js +146 -0
  79. package/web/app/core/rules.js +163 -0
  80. package/web/app/core/selection.js +80 -0
  81. package/web/app/core/zoom.js +41 -0
  82. package/web/app/formula-bar.js +175 -0
  83. package/web/app/function-catalog.js +250 -0
  84. package/web/app/function-search.js +155 -0
  85. package/web/app/grid/edit.js +187 -0
  86. package/web/app/grid/fill.js +64 -0
  87. package/web/app/grid/formula.js +87 -0
  88. package/web/app/grid/keys.js +171 -0
  89. package/web/app/grid/menus.js +34 -0
  90. package/web/app/grid/mouse.js +282 -0
  91. package/web/app/grid/render.js +255 -0
  92. package/web/app/grid/resize.js +176 -0
  93. package/web/app/grid/shared.js +10 -0
  94. package/web/app/grid-menu.js +132 -0
  95. package/web/app/grid.js +157 -0
  96. package/web/app/main.js +10 -0
  97. package/web/app/sheet-tabs.js +47 -0
  98. package/web/app/sheets-app.js +816 -0
  99. package/web/app/toolbar.js +832 -0
  100. package/web/app/ui/color-panel.js +143 -0
  101. package/web/app/ui/dialogs.js +86 -0
  102. package/web/app/ui/file-io.js +67 -0
  103. package/web/app/ui/filter-panel.js +298 -0
  104. package/web/app/ui/find-replace.js +329 -0
  105. package/web/app/ui/formula-suggest.js +346 -0
  106. package/web/app/ui/function-dialog.js +127 -0
  107. package/web/app/ui/icons.js +54 -0
  108. package/web/app/ui/image-viewer.js +86 -0
  109. package/web/app/ui/menu.js +182 -0
  110. package/web/app/ui/notify.js +45 -0
  111. package/web/app/ui/print-preview.js +473 -0
  112. package/web/app/ui/prompt.js +135 -0
  113. package/web/app/ui/shape-dom.js +63 -0
  114. package/web/app/ui/thread-panel.js +192 -0
  115. package/web/index.html +31 -0
  116. package/web/serve.mjs +21 -0
  117. package/web/styles/base.css +48 -0
  118. package/web/styles/sheets.css +2516 -0
  119. package/web/styles/tokens.css +73 -0
  120. package/src/internal/text-utils.js +0 -18
package/README.md CHANGED
@@ -1,18 +1,19 @@
1
1
  # gbxlxs
2
2
 
3
- 独立电子表格引擎:**读写真正的 `.xlsx`、工作簿模型操作、CSV / HTML 导入导出**。
3
+ 独立电子表格引擎:**读写真正的 `.xlsx`、工作簿模型操作、CSV / HTML 导入导出,外加一个自包含的 HTML 表格编辑器**。
4
4
 
5
5
  它不是某个在线表格的封装,而是一层可以直接嵌进任何前端的表格内核:解析 OOXML 得到一个纯对象模型,用同步算子改这个模型,再序列化回 `.xlsx`,并在往返中尽量保住原文件的边角内容(图表、图片、透视表、条件格式、打印分节等)。ZIP 与 XML 这两个底层难题全部交给 [`gbooxml`](https://www.npmjs.com/package/gbooxml)。
6
6
 
7
- ## 三层结构
7
+ ## 四层结构
8
8
 
9
9
  | 层 | 入口 | 职责 |
10
10
  | --- | --- | --- |
11
11
  | 引擎 | `gbxlxs/workbook` | `.xlsx` 读写、CSV 导出、HTML 导入、数字格式、行列插删 |
12
12
  | 算子 | `gbxlxs/ops` | 对工作簿/分节对象做**同步就地修改**:取值、写值、公式、样式、合并、排序、筛选、冻结、分节增删改名 |
13
13
  | 会话 | `gbxlxs/session` | 托管一份文档:脏标记、自动序列化、失败上报、修订号握手 |
14
+ | 界面 | `web/` | 原生 HTML 表格编辑器:菜单、工具带、公式栏、窗口化网格、页签、右键菜单 |
14
15
 
15
- 根入口 `gbxlxs` 把三层的 68 个名字一次性全部导出,日常用 `import { openXlsx, setValue } from 'gbxlxs'` 就够了。
16
+ 根入口 `gbxlxs` 把引擎/算子/会话的 91 个名字一次性全部导出,日常用 `import { openXlsx, setValue } from 'gbxlxs'` 就够了。
16
17
 
17
18
  ## 安装
18
19
 
@@ -20,15 +21,59 @@
20
21
  npm install gbxlxs
21
22
  ```
22
23
 
24
+ ## 界面
25
+
26
+ `web/` 是一套不打包、不依赖框架的完整表格编辑器,引擎仍走本包:
27
+
28
+ ```bash
29
+ npm start # 等价于 node web/serve.mjs
30
+ # http://localhost:5275/web/
31
+ ```
32
+
33
+ 包含打开 / 保存 / 另存为 `.xlsx`、新建、CSV 导出、自动保存(浏览器文件句柄)、深色主题、缩放(工具栏、Ctrl+滚轮以指针为锚)、冻结窗格、筛选、合并、排序、数字格式、条件格式、数据验证、批注、超链接、复选框、图片预览、拖放打开、撤销重做与剪贴板;公式在本地实时求值,输入函数名时弹出候选列表(↑↓ 选择、Enter/Tab 插入、Esc 收起),函数参数处显示签名与必填/可选说明;提供自动求和、可搜索的插入函数对话框、函数分类菜单,列宽/行高支持拖拽与双击自适应,填充柄支持复制、数字/日期序列与公式相对引用平移。`index.html` 通过 import map 把 `gbooxml` / `guabiutils` 指到 `/vendor/*`,`serve.mjs`(薄封装,本体在 `guabiutils/dev-server`)负责静态供给,无需构建。
34
+
35
+ 也可以把编辑器嵌进现有前端(不依赖 Vue,导出路径为 `gbxlxs/web/*`):
36
+
37
+ ```js
38
+ import { SheetEditor } from 'gbxlxs/web/app/sheets-app.js';
39
+
40
+ const editor = new SheetEditor(mountEl, {
41
+ embedded: true, // 文件级动作交给宿主
42
+ host: {
43
+ getTitle: () => '销售.xlsx',
44
+ getPath: () => '文档/表格',
45
+ getStatus: () => ({ text: '已保存', kind: '' }),
46
+ getAutoSave: () => true,
47
+ setAutoSave: (on) => {},
48
+ canSave: () => true,
49
+ save: async () => true, // 宿主负责把 serializeNow() 的字节写回
50
+ saveAs: async () => true,
51
+ open: () => {},
52
+ create: () => {},
53
+ recentList: () => [],
54
+ openRecent: (doc) => {},
55
+ onChange: ({ dirty, error }) => {},
56
+ },
57
+ });
58
+
59
+ await editor.openBytes(bytes); // 或 await editor.createBlank()
60
+ const out = await editor.serializeNow();
61
+ editor.dispose();
62
+ ```
63
+
64
+ 不传 `host` / `embedded` 时即独立模式,编辑器自己处理文件选择、保存与未保存确认。
65
+
23
66
  ## 导入路径
24
67
 
25
- `exports` 只声明了五个键,**没有通配**,因此深层路径会被 Node 直接拒掉:
68
+ `exports` 声明了四个引擎入口与一个 `web/` 通配;`src/` 深层路径仍会被 Node 直接拒掉:
26
69
 
27
70
  ```js
28
- import { openXlsx } from 'gbxlxs'; // 根入口,全部 68 个名字
71
+ import { openXlsx } from 'gbxlxs'; // 根入口,全部 91 个名字
29
72
  import { openXlsx } from 'gbxlxs/workbook'; // 只要引擎层
30
73
  import { setValue } from 'gbxlxs/ops'; // 只要算子层
31
74
  import { createSheetSession } from 'gbxlxs/session';
75
+ import { SheetEditor } from 'gbxlxs/web/app/sheets-app.js';
76
+ import 'gbxlxs/web/styles/sheets.css';
32
77
  import version from 'gbxlxs/package.json' with { type: 'json' };
33
78
  ```
34
79
 
@@ -72,18 +117,50 @@ const bytes = await writeXlsx({
72
117
 
73
118
  `saveXlsx` 和 `writeXlsx` 是两条不同的路:`saveXlsx` 走**保真往返**,只接受 `openXlsx` 产出的工作簿;`writeXlsx` 从裸模型重新生成全部 OOXML。把一个手工拼出来的对象交给 `saveXlsx` 会抛 `InvalidArgumentError`。
74
119
 
120
+ ### 导出一张表(`writeTableXlsx`)
121
+
122
+ 只是要把「表头 + 行」导成 Excel 时不用拼工作簿模型:列定义、表头样式、冻结首行、自动筛选与列宽一次配好。
123
+
124
+ ```js
125
+ import { writeTableXlsx } from 'gbxlxs';
126
+
127
+ const bytes = await writeTableXlsx({
128
+ name: '任务',
129
+ columns: [
130
+ { title: '名称', key: 'name', width: 40 },
131
+ { title: '负责人', key: 'owner' },
132
+ { title: '截止', key: 'end' },
133
+ { title: '数量', key: 'count', numFmt: '#,##0', align: 'right' },
134
+ ],
135
+ rows: [
136
+ { name: '写文档', owner: '李娜', end: '2026-11-01', count: 3 },
137
+ ['评审', '王强', '2026-11-02', 1], // 也可以给数组(按列序)
138
+ ],
139
+ });
140
+
141
+ // 多张表:{ sheets: [{ name, columns, rows }, …], defaultFont, dateSystem }
142
+ ```
143
+
144
+ - **列**:`title` 必填(表头文案,也是对象行的默认取值键);`key` / `width` / `numFmt` / `align`(`center` / `right`)/ `style` 可选。`numFmt` 与 `align` 落到该列每个数据格上。
145
+ - **行**:数组按列序、对象按 `key` 取值;`null` / `undefined` / `""` 落成空格;数字 / 布尔 / `Date` 原样保留类型;`{ value, style, hyperlink }` 内联单元格对象透传。**不做类型推断**(`"00123"` 仍是文本)。
146
+ - **版式**:`header`(默认 `true`)出表头行(加粗 + 浅灰底 + 居中 + 下细线,`headerStyle` 可整份替换),`freezeHeader`(默认 `true`)冻结首行,`autoFilter`(默认 `true`)给「表头 + 数据」加自动筛选,`autoWidth`(默认 `true`)按内容算列宽(8–60 字符;给了 `width` 的列以 `width` 为准,`autoWidth: false` 则只写显式宽度)。
147
+ - 顶层另接受 `defaultFont` / `dateSystem` / `stringMode` / `activeSheet`,原样传给 `writeXlsx`。
148
+ - 参数不合法(空列、空标题、行里塞数组或普通对象、一行给的值比列多、`sheets` 与 `columns` 混用)一律抛 `InvalidArgumentError`,不会静默写出半张表。
149
+
75
150
  ### 公式
76
151
 
77
152
  ```js
78
- import { setFormula, getFormula, insertRows } from 'gbxlxs';
153
+ import { setFormula, getFormula, recalculateWorkbook, insertRows } from 'gbxlxs';
79
154
 
80
- setFormula(sheet, 1, 1, 'SUM(A2:A5)', 100); // 公式不带前导 =,第 4 个参数是缓存结果
155
+ setFormula(sheet, 1, 1, 'SUM(A2:A5)'); // 公式不带前导 =;第 4 个参数可传缓存值
156
+ recalculateWorkbook(wb); // 本地求值,写回每格的 formulaResult
81
157
  getFormula(sheet, 1, 1); // 'SUM(A2:A5)'
158
+ sheet.rows[1][1]; // 计算结果
82
159
 
83
160
  insertRows(sheet, 1, 1); // 在第 2 行插一行,引用自动下移
84
161
  ```
85
162
 
86
- 行列插删、隐藏、移动这类结构算子会自动重映射 `cells` 的键、公式引用、合并区、图片锚点、冻结线和分页符 —— 前提是先调用过 `linkWorkbookSheets(wb)`(`openXlsx` 与 `addSheet` 已经替你做这一步),否则跨表引用不会被同步。
163
+ 引擎自带公式解析与求值:支持单元格/区域/跨表引用、定义名称、共享公式、错误值与循环检测,内置 230+ 个函数(数学、统计、文本、日期、逻辑、查找、财务、工程、信息、数据库)。`recalculateWorkbook(wb, { keepCached: true })` 会在打开文件时保留无法识别函数的原缓存值,编辑时再暴露 `#NAME?`。行列插删、隐藏、移动这类结构算子会自动重映射 `cells` 的键、公式引用、合并区、图片锚点、冻结线和分页符 —— 前提是先调用过 `linkWorkbookSheets(wb)`(`openXlsx` 与 `addSheet` 已经替你做这一步),否则跨表引用不会被同步。
87
164
 
88
165
  ### 样式与数字格式
89
166
 
@@ -113,6 +190,68 @@ setFreeze(sheet, 1, 0); // 冻结首行
113
190
 
114
191
  排序的首行识别规则:该行是**非空字符串**,且同列数据区里存在非字符串值,或者该格 `style.font.bold === true`。混合类型排序为 数字/日期 < 文本 < 布尔,空值永远排最后(即使 `desc`)。
115
192
 
193
+ ### 高级筛选(条件 / 空白 / 颜色 / 列间且或)
194
+
195
+ ```js
196
+ import { setFilterCriteria, setFilterLogic, filterCriteria, filterColorOptions, rowMatchesFilter } from 'gbxlxs';
197
+
198
+ setFilterCriteria(sheet, 1, { customFilters: { and: true, customFilters: [
199
+ { operator: 'greaterThan', value: 100 },
200
+ { operator: 'lessThanOrEqual', value: 500 },
201
+ ] } }); // 100 < x <= 500
202
+ setFilterCriteria(sheet, 2, { filters: ['北京'], blank: true }); // 按值 + 带空白
203
+ setFilterCriteria(sheet, 3, { colorFilters: { cellFillColors: ['FFCC00'] } });
204
+ setFilterCriteria(sheet, 1, null); // 清除该列条件
205
+ setFilterLogic(sheet, 'or'); // 列间关系:任一条件满足
206
+ rowMatchesFilter(sheet, 5); // 单行是否通过(标题行恒为 true)
207
+ ```
208
+
209
+ `operator` 取 `equal / notEqual / greaterThan / greaterThanOrEqual / lessThan / lessThanOrEqual / beginsWith / endsWith / contains / notContains`;等于/不等于支持 `*` 与 `?` 通配符。筛选隐藏的行由引擎单独记账,**取消筛选不会把用户手动隐藏的行放出来**。条件随 xlsx 的 `customFilters` / `colorFilter` 往返。
210
+
211
+ ### 查找与替换
212
+
213
+ ```js
214
+ import { findInSheet, findInWorkbook, replaceInSheet, replaceInWorkbook, replaceMatch } from 'gbxlxs';
215
+
216
+ const hits = findInWorkbook(wb, '订单-\\d+', { useRegex: true, matchCase: false, inFormulas: true });
217
+ // → [{ sheetIndex, sheetName, row, col, start, end, text, cellText, inFormula }]
218
+ replaceInWorkbook(wb, '旧值', '新值', { matchEntireCell: true }); // → { count, changes }
219
+ replaceMatch(sheet, hits[0], '新值'); // 单个命中(UI「替换」按钮口径)
220
+ ```
221
+
222
+ 选项:`matchCase`、`matchEntireCell`(同义 `wholeCell`)、`useRegex`、`inFormulas`(同义 `lookin: 'formulas'`)、`byFormat` + `formatStyle`、`range`、`sheetIndex`。`replaceIn*` 是「全部替换」口径(格内多处出现一次换净),`replaceMatch` 只换命中处;返回的 `changes` 可直接交给历史栈撤销。无效的正则会抛「正则表达式无效」。
223
+
224
+ ### 超级表结构化引用与动态数组
225
+
226
+ ```js
227
+ import { setFormula, recalculateWorkbook } from 'gbxlxs';
228
+
229
+ setFormula(sheet, 9, 1, 'SUM(销售表[金额])'); // 列、[列]:[列]、[#全部]、[#数据]
230
+ setFormula(sheet, 9, 2, '销售表[[#标题],[金额]]'); // [#标题] / [#总计]
231
+ setFormula(sheet, 2, 5, '@单价 * @数量'); // @ 与 [#此行] 取当前行
232
+ setFormula(sheet, 0, 5, 'SORT(A2:A10)'); // 数组结果自动溢出,冲突返回 #SPILL!
233
+ setFormula(sheet, 0, 8, 'LET(x, 10, x * 2)'); // LET / LAMBDA 已可求值
234
+ recalculateWorkbook(wb);
235
+ ```
236
+
237
+ 表名或列名对不上返回 `#NAME?`,节不合法(如无标题行却要 `[#标题]`)返回 `#REF!`。溢出区的值写在 `spillParent` 标记的格子上,重算前会被清掉,不会污染用户数据。
238
+
239
+ ### 打印分页、线程评论与形状
240
+
241
+ ```js
242
+ import { paginateSheet, normalizePrintSetup, addThread, replyThread, threadGroups } from 'gbxlxs';
243
+
244
+ const g = { colWidths: [...], rowHeights: [...] }; // 未缩放的 96dpi 像素尺寸
245
+ const { pages, setup } = paginateSheet(sheet, g); // 按打印区域/标题/分页符/缩放切页
246
+ normalizePrintSetup(sheet); // 页面设置 → 像素与选项
247
+
248
+ addThread(sheet, wb, 0, 0, '这里需要复核', '张三'); // 线程评论(legacy comment 仍是备注)
249
+ replyThread(sheet, wb, rootId, '已改');
250
+ threadGroups(sheet, wb, 0, 0); // → [{ author, replies, done }]
251
+ ```
252
+
253
+ `sheet.shapes` / `sheet.textBoxes` 随 xlsx 往返,插删行列时锚点自动同步。`paginateSheet` 只算分页,渲染交给 UI(Web 编辑器的打印预览即基于此,走浏览器打印对话框另存 PDF)。
254
+
116
255
  ### CSV 导出与 HTML 导入
117
256
 
118
257
  ```js
@@ -157,9 +296,12 @@ await session.serializeNow(); // 立即拿当前 Uint8Array
157
296
  merges: [{ startRow: 0, startCol: 0, endRow: 0, endCol: 1 }],
158
297
  freezePane: { rows: 1 },
159
298
  autoFilter: { range: 'A1:D9', columns: [{ colIndex: 0, filters: ['a'] }] },
299
+ threadedComments: [{ id, personId, ref: 'A1', date, text, parentId?, done? }],
300
+ shapes: [{ type: 'rect', text, anchor: { from: { row, col }, to: { row, col } }, width, height, style }],
160
301
  // 还可能有:dataValidations, conditionalRules, images, charts, tables,
161
302
  // textBoxes, pageSetup, headerFooter, protection, sparklines, …
162
303
  }],
304
+ persons: [{ id, displayName }],
163
305
  dateSystem: '1900',
164
306
  activeSheet: 0,
165
307
  namedRanges: [{ name, range, scope }],
@@ -181,14 +323,16 @@ await session.serializeNow(); // 立即拿当前 Uint8Array
181
323
 
182
324
  | 组 | 名字 |
183
325
  | --- | --- |
184
- | 打开/保存 | `openXlsx`、`saveXlsx`、`writeXlsx`、`fromHtml`、`writeCsv` |
326
+ | 打开/保存 | `openXlsx`、`saveXlsx`、`writeXlsx`、`writeTableXlsx`、`fromHtml`、`writeCsv` |
185
327
  | 读格 | `getEntry`、`getValue`、`getDisplayText`、`getFormula`、`getStyle`、`keyOf`、`isProtected` |
186
328
  | 写格 | `setValue`、`setFormula`、`setStyle`、`setFont`、`setCellExtra`、`replaceStyle`、`clearStyle`、`parseInput` |
187
329
  | 快照/撤销 | `captureCell`、`applyCell`、`captureRegion` |
188
330
  | 行列结构 | `insertRows`、`deleteRows`、`hideRows`、`insertColumns`、`deleteColumns`、`hideColumns`、`unhideAll`、`setFreeze` |
189
331
  | 分节 | `addSheet`、`removeSheetAt`、`renameSheetAt`、`linkWorkbookSheets` |
190
332
  | 区域 | `normalizeRegion`、`regionA1`、`cellHasContent`、`currentRegion`、`regionsOverlap`、`mergeAt`、`mergeRegion`、`unmergeRegion` |
191
- | 排序/筛选 | `compareKey`、`sortRegion`、`toggleFilter`、`applyFilter`、`clearFilter`、`filterOptions`、`hasFilter` |
333
+ | 排序/筛选 | `compareKey`、`sortRegion`、`toggleFilter`、`applyFilter`、`clearFilter`、`filterOptions`、`filterColorOptions`、`filterCriteria`、`setFilterCriteria`、`setFilterLogic`、`filterLogic`、`rowMatchesFilter`、`hasFilter` |
334
+ | 查找替换 | `findInSheet`、`findInWorkbook`、`replaceMatch`、`replaceInSheet`、`replaceInWorkbook` |
335
+ | 打印分页 | `paginateSheet`、`normalizePrintSetup` |
192
336
  | 格式 | `formatValue`、`inferType`、`cloneCellStyle`、`shiftedPattern`、`applyNumfmt`、`currentNumfmt`、`applyBorder` |
193
337
  | 引用工具 | `parseCellRef`、`cellRef`、`colToLetter`、`letterToCol`、`parseRange`、`isInRange`、`replaceA1Refs` |
194
338
  | 校验常量 | `FORBIDDEN_SHEET_NAME_CHARS`、`MAX_SHEET_NAME_LENGTH`、`RESERVED_SHEET_NAME` |
package/package.json CHANGED
@@ -1,34 +1,42 @@
1
1
  {
2
2
  "name": "gbxlxs",
3
- "version": "0.1.2",
4
- "description": "Standalone spreadsheet (XLSX) engine: read/write xlsx, workbook model ops and CSV/HTML import-export.",
3
+ "version": "0.1.6",
4
+ "description": "Standalone spreadsheet (XLSX) engine with a self-contained HTML editor: read/write xlsx, workbook model ops, CSV/HTML import-export and a full spreadsheet UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
- "sideEffects": false,
7
+ "sideEffects": [
8
+ "**/*.css"
9
+ ],
8
10
  "main": "./src/index.js",
9
11
  "exports": {
10
12
  ".": "./src/index.js",
11
13
  "./ops": "./src/ops.js",
12
14
  "./session": "./src/session.js",
13
15
  "./workbook": "./src/workbook/index.js",
16
+ "./web/*": "./web/*",
14
17
  "./package.json": "./package.json"
15
18
  },
16
19
  "files": [
17
20
  "src",
21
+ "web",
18
22
  "LICENSE"
19
23
  ],
20
24
  "scripts": {
21
- "test": "node --test test/editing.test.js test/references.test.js test/session.test.js test/roundtrip.test.js"
25
+ "start": "node web/serve.mjs",
26
+ "test": "node --test test/editing.test.js test/references.test.js test/session.test.js test/roundtrip.test.js test/scenarios.test.js test/ops-scenarios.test.js test/formula.test.js test/function-search.test.js test/find-replace.test.js test/advanced-filter.test.js test/structured-refs.test.js test/dynamic-array.test.js test/print.test.js test/threaded-comments.test.js test/shapes.test.js test/table-export.test.js"
22
27
  },
23
28
  "dependencies": {
24
- "gbooxml": "^0.1.0"
29
+ "gbooxml": "^0.1.3",
30
+ "guabiutils": "^0.3.0"
25
31
  },
26
32
  "keywords": [
27
33
  "xlsx",
28
34
  "excel",
29
35
  "spreadsheet",
30
36
  "ooxml",
31
- "workbook"
37
+ "workbook",
38
+ "editor",
39
+ "ui"
32
40
  ],
33
41
  "engines": {
34
42
  "node": ">=18"
@@ -0,0 +1,251 @@
1
+ // [文件] gbxlxs·查找替换——按显示值/公式/格式检索区域或整本工作簿,返回可撤销的替换变更
2
+ import { captureCell, getDisplayText, getEntry, getStyle, normalizeRegion, parseInput, setFormula, setValue } from './ops.js';
3
+ import { isInRange } from './workbook/index.js';
4
+
5
+ const styleKey = (value) => {
6
+ if (value === null || value === undefined) return '';
7
+ if (Array.isArray(value)) return `[${value.map(styleKey).join(',')}]`;
8
+ if (typeof value === 'object') {
9
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${styleKey(value[key])}`).join(',')}}`;
10
+ }
11
+ return JSON.stringify(value);
12
+ };
13
+
14
+ const sameStyle = (a, b) => styleKey(a) === styleKey(b);
15
+
16
+ const sheetBounds = (sheet) => {
17
+ let rows = sheet?.rows?.length || 0;
18
+ let cols = sheet?.columns?.length || 0;
19
+ for (const row of sheet?.rows || []) if (row.length > cols) cols = row.length;
20
+ for (const key of sheet?.cells?.keys() || []) {
21
+ const comma = key.indexOf(',');
22
+ if (comma < 0) continue;
23
+ const row = Number(key.slice(0, comma));
24
+ const col = Number(key.slice(comma + 1));
25
+ if (row + 1 > rows) rows = row + 1;
26
+ if (col + 1 > cols) cols = col + 1;
27
+ }
28
+ for (const merge of sheet?.merges || []) {
29
+ if (merge.endRow + 1 > rows) rows = merge.endRow + 1;
30
+ if (merge.endCol + 1 > cols) cols = merge.endCol + 1;
31
+ }
32
+ return { rows, cols };
33
+ };
34
+
35
+ const matcherOf = (query, { useRegex = false, matchCase = false } = {}) => {
36
+ if (useRegex) {
37
+ try {
38
+ return new RegExp(query, matchCase ? '' : 'i');
39
+ } catch {
40
+ throw new Error('正则表达式无效');
41
+ }
42
+ }
43
+ if (!query) return null;
44
+ const needle = matchCase ? String(query) : String(query).toLowerCase();
45
+ return { exec: (text) => {
46
+ const haystack = matchCase ? text : text.toLowerCase();
47
+ const index = haystack.indexOf(needle);
48
+ return index < 0 ? null : { index, length: needle.length, text: text.slice(index, index + needle.length) };
49
+ } };
50
+ };
51
+
52
+ const matchInText = (regex, text, { matchEntireCell = false } = {}) => {
53
+ if (!text && !matchEntireCell) return null;
54
+ if (regex instanceof RegExp) {
55
+ regex.lastIndex = 0;
56
+ const match = regex.exec(text);
57
+ if (!match) return null;
58
+ if (matchEntireCell && (match.index !== 0 || match[0].length !== text.length)) return null;
59
+ return { start: match.index, end: match.index + match[0].length, text: match[0] };
60
+ }
61
+ const match = regex.exec(text);
62
+ if (!match) return null;
63
+ if (matchEntireCell && (match.index !== 0 || match.length !== text.length)) return null;
64
+ return { start: match.index, end: match.index + match.length, text: match.text };
65
+ };
66
+
67
+ const isMergedFollower = (sheet, row, col) =>
68
+ Boolean(sheet?.merges?.some((merge) => isInRange(row, col, merge) && !(merge.startRow === row && merge.startCol === col)));
69
+
70
+ const searchTextOf = (sheet, row, col, inFormulas) => {
71
+ const entry = getEntry(sheet, row, col);
72
+ if (inFormulas && entry?.formula) return `=${entry.formula}`;
73
+ return getDisplayText(sheet, row, col);
74
+ };
75
+
76
+ const normalizeOptions = (options = {}) => ({
77
+ matchCase: options.matchCase === true,
78
+ matchEntireCell: options.matchEntireCell === true || options.wholeCell === true,
79
+ useRegex: options.useRegex === true || options.regex === true,
80
+ inFormulas: options.inFormulas === true || options.lookin === 'formulas',
81
+ byFormat: options.byFormat === true,
82
+ formatStyle: options.formatStyle ?? null,
83
+ range: options.range ? normalizeRegion(
84
+ options.range.startRow,
85
+ options.range.startCol ?? options.range.startColumn,
86
+ options.range.endRow,
87
+ options.range.endCol ?? options.range.endColumn,
88
+ ) : null,
89
+ });
90
+
91
+ const collectMatches = (sheet, sheetIndex, query, options) => {
92
+ if (!query && !options.byFormat) return [];
93
+ const matcher = options.byFormat && !query ? null : matcherOf(query, options);
94
+ const bounds = sheetBounds(sheet);
95
+ const region = options.range || { startRow: 0, startCol: 0, endRow: Math.max(0, bounds.rows - 1), endCol: Math.max(0, bounds.cols - 1) };
96
+ const out = [];
97
+ for (let row = region.startRow; row <= region.endRow; row++) {
98
+ for (let col = region.startCol; col <= region.endCol; col++) {
99
+ if (isMergedFollower(sheet, row, col)) continue;
100
+ if (options.byFormat && !sameStyle(getStyle(sheet, row, col), options.formatStyle)) continue;
101
+ const text = searchTextOf(sheet, row, col, options.inFormulas);
102
+ if (!text && !options.matchEntireCell) continue;
103
+ if (!matcher) {
104
+ if (text) out.push({ sheetIndex, sheetName: sheet.name, row, col, start: 0, end: text.length, text, query, inFormula: Boolean(options.inFormulas && getEntry(sheet, row, col)?.formula) });
105
+ continue;
106
+ }
107
+ const match = matchInText(matcher, text, options);
108
+ if (!match) continue;
109
+ out.push({
110
+ sheetIndex,
111
+ sheetName: sheet.name,
112
+ row,
113
+ col,
114
+ start: match.start,
115
+ end: match.end,
116
+ text: match.text,
117
+ cellText: text,
118
+ query,
119
+ inFormula: Boolean(options.inFormulas && getEntry(sheet, row, col)?.formula),
120
+ });
121
+ }
122
+ }
123
+ return out;
124
+ };
125
+
126
+ export function findInSheet(sheet, query, options = {}) {
127
+ if (!sheet) return [];
128
+ const opts = normalizeOptions(options);
129
+ return collectMatches(sheet, options.sheetIndex ?? 0, String(query ?? ''), opts);
130
+ }
131
+
132
+ export function findInWorkbook(workbook, query, options = {}) {
133
+ if (!workbook?.sheets?.length) return [];
134
+ const opts = normalizeOptions(options);
135
+ const out = [];
136
+ for (let index = 0; index < workbook.sheets.length; index++) {
137
+ const sheet = workbook.sheets[index];
138
+ if (!sheet || sheet.hidden) continue;
139
+ // 区域查找只对指定工作表生效,避免把同一 A1 区套到所有表
140
+ const sheetOpts = opts.range && options.sheetIndex !== index ? { ...opts, range: null } : opts;
141
+ out.push(...collectMatches(sheet, index, String(query ?? ''), sheetOpts));
142
+ }
143
+ return out;
144
+ }
145
+
146
+ // [设计] 逐段拼接替换,不用 lowercase 文本拼接结果——否则大小写不敏感替换会把原文本整体小写化
147
+ const replaceAllPlain = (text, query, replacement, options) => {
148
+ const needle = String(query ?? '');
149
+ if (!needle) return null;
150
+ const haystack = options.matchCase ? text : text.toLowerCase();
151
+ const target = options.matchCase ? needle : needle.toLowerCase();
152
+ let out = '';
153
+ let at = 0;
154
+ let hit = false;
155
+ for (;;) {
156
+ const index = haystack.indexOf(target, at);
157
+ if (index < 0) break;
158
+ hit = true;
159
+ out += text.slice(at, index) + replacement;
160
+ at = index + target.length;
161
+ }
162
+ if (!hit) return null;
163
+ out += text.slice(at);
164
+ return out === text ? null : out;
165
+ };
166
+
167
+ const replaceText = (text, query, replacement, options, firstOnly) => {
168
+ if (options.useRegex) {
169
+ const matcher = matcherOf(query, options);
170
+ if (!matcher) return null;
171
+ const flags = `${matcher.flags.replace('g', '')}${firstOnly ? '' : 'g'}`;
172
+ const next = text.replace(new RegExp(matcher.source, flags), replacement);
173
+ return next === text ? null : next;
174
+ }
175
+ if (!query) return null;
176
+ if (!firstOnly) return replaceAllPlain(text, query, replacement, options);
177
+ const matcher = matcherOf(query, options);
178
+ if (!matcher) return null;
179
+ const match = matchInText(matcher, text, options);
180
+ if (!match) return null;
181
+ return text.slice(0, match.start) + replacement + text.slice(match.end);
182
+ };
183
+
184
+ /**
185
+ * 替换一个查找命中(match 来自 findInSheet/findInWorkbook)。
186
+ * [设计] 公式命中写回公式文本;其余命中写显示值。整格替换时按输入规则推断数字/日期类型。
187
+ * options.all=true(批量替换)时替换格内全部出现,否则只替换命中处(与 Excel「替换」按钮一致)。
188
+ */
189
+ export function replaceMatch(sheet, match, replacement, options = {}) {
190
+ if (!sheet || !match) return null;
191
+ const opts = normalizeOptions(options);
192
+ const firstOnly = options.all !== true;
193
+ const entry = getEntry(sheet, match.row, match.col);
194
+ if (opts.byFormat && !sameStyle(getStyle(sheet, match.row, match.col), opts.formatStyle)) return null;
195
+ const before = captureCell(sheet, match.row, match.col);
196
+ const query = options.query ?? match.query ?? match.text;
197
+ if (opts.inFormulas && entry?.formula) {
198
+ const text = `=${entry.formula}`;
199
+ const next = replaceText(text, query, replacement, opts, firstOnly);
200
+ if (next === null) return null;
201
+ if (next.startsWith('=')) {
202
+ setFormula(sheet, match.row, match.col, next.slice(1), entry.formulaResult ?? null);
203
+ } else {
204
+ setValue(sheet, match.row, match.col, next);
205
+ }
206
+ } else {
207
+ const text = getDisplayText(sheet, match.row, match.col);
208
+ let next;
209
+ if (opts.matchEntireCell) {
210
+ // [设计] 整格替换不再保留原文本;原来是非文本格时按输入规则还原数字/日期类型
211
+ next = typeof before?.value === 'string' || before?.value === null ? replacement : parseInput(replacement).value;
212
+ } else {
213
+ next = replaceText(text, query, replacement, opts, firstOnly);
214
+ if (next === null) return null;
215
+ }
216
+ setValue(sheet, match.row, match.col, next);
217
+ }
218
+ const after = captureCell(sheet, match.row, match.col);
219
+ return { sheet, sheetIndex: match.sheetIndex, row: match.row, col: match.col, before, after, match };
220
+ }
221
+
222
+ /** 区域内批量替换;返回 { count, changes },changes 可直接交给历史栈。 */
223
+ export function replaceInSheet(sheet, query, replacement, options = {}) {
224
+ if (!sheet) return { count: 0, changes: [] };
225
+ const opts = normalizeOptions(options);
226
+ const matches = collectMatches(sheet, options.sheetIndex ?? 0, String(query ?? ''), opts);
227
+ const changes = [];
228
+ for (const match of matches) {
229
+ const change = replaceMatch(sheet, match, replacement, { ...options, ...opts, query, all: true });
230
+ if (change) changes.push(change);
231
+ }
232
+ return { count: changes.length, changes };
233
+ }
234
+
235
+ export function replaceInWorkbook(workbook, query, replacement, options = {}) {
236
+ if (!workbook?.sheets?.length) return { count: 0, changes: [] };
237
+ const opts = normalizeOptions(options);
238
+ const changes = [];
239
+ for (let index = 0; index < workbook.sheets.length; index++) {
240
+ const sheet = workbook.sheets[index];
241
+ if (!sheet || sheet.hidden) continue;
242
+ const sheetOpts = opts.range && options.sheetIndex !== index ? { ...opts, range: null } : opts;
243
+ const matches = collectMatches(sheet, index, String(query ?? ''), sheetOpts);
244
+ for (const match of matches) {
245
+ const change = replaceMatch(sheet, match, replacement, { ...options, ...sheetOpts, sheetIndex: index, query, all: true });
246
+ if (change) changes.push(change);
247
+ }
248
+ }
249
+ return { count: changes.length, changes };
250
+ }
251
+
package/src/index.js CHANGED
@@ -3,6 +3,17 @@
3
3
  export * from './workbook/index.js';
4
4
  export * from './session.js';
5
5
  export * from './ops.js';
6
+ export * from './find-replace.js';
7
+ export * from './print.js';
8
+ // [设计] 线程评论原语走显式具名再导出:与 print/find-replace 一样属于包公开面,
9
+ // 但不用 export * —— 避免将来与 workbook/ops 的同名导出静默互相覆盖。
10
+ export {
11
+ addThread,
12
+ replyThread,
13
+ setThreadDone,
14
+ deleteThread,
15
+ threadGroups,
16
+ } from './threaded-comments.js';
6
17
  // [设计] workbook 与 ops 双侧同名(ops 转发结构操作):显式从 workbook 再导出以消歧义,
7
18
  // 否则 export * 遇到重名会静默丢弃该名字。
8
19
  export {