@file-viewer/renderer-spreadsheet 3.3.0 → 3.3.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/README.en.md CHANGED
@@ -37,6 +37,8 @@ const options = {
37
37
  - Supports multiple sheets, horizontally scrollable sheet tabs, merged cells, row and column sizing, borders, fills, alignment, text color, Office 365 and WPS in-cell images, workbook drawing images, double-click image previews, the global zoom provider, and optional header drag column resizing.
38
38
  - TIFF drawings in XLSX files load the MIT-licensed UTIF.js decoder only when needed and are converted to PNG in the browser. Ordinary spreadsheets do not load the TIFF decoder.
39
39
  - Uses virtual rendering for interaction. Host components usually hide full-document print for spreadsheets to avoid printing only the current viewport.
40
+ - XLSX uses saved default and explicit column widths and point-based row heights. CSV/TSV retains content auto-fit and supports large decoded text without creating a second UTF-8 byte array.
41
+ - Column units follow the workbook's Normal style. SimSun/NSimSun digit advances are converted from points before rounding; unmeasured custom fonts retain the standard fallback, so exact geometry can depend on the font.
40
42
 
41
43
  ## Fill the viewport for small Excel sheets
42
44
 
@@ -50,7 +52,7 @@ const options = {
50
52
  }
51
53
  ```
52
54
 
53
- This changes only the display: workbook data, used range, original-file downloads/exports, search results and content counts remain unchanged. CSV / TSV / ODS / Numbers ignore this option. Omitting it or setting it to `false` preserves the existing behavior.
55
+ This changes only the display: workbook data, used range, original-file downloads/exports, search results and content counts remain unchanged.
54
56
 
55
57
  ## Offline Assets
56
58
 
package/README.md CHANGED
@@ -37,6 +37,8 @@ const options = {
37
37
  - Supports multiple sheets, horizontally scrollable sheet tabs, merged cells, row and column sizing, borders, fills, alignment, text color, Office 365 and WPS in-cell images, workbook drawing images, double-click image previews, the global zoom provider, and optional header drag column resizing.
38
38
  - TIFF drawings in XLSX files load the MIT-licensed UTIF.js decoder only when needed and are converted to PNG in the browser. Ordinary spreadsheets do not load the TIFF decoder.
39
39
  - Uses virtual rendering for interaction. Host components usually hide full-document print for spreadsheets to avoid printing only the current viewport.
40
+ - XLSX uses saved default and explicit column widths and point-based row heights. CSV/TSV retains content auto-fit and supports large decoded text without creating a second UTF-8 byte array.
41
+ - Column units follow the workbook's Normal style. SimSun/NSimSun digit advances are converted from points before rounding; unmeasured custom fonts retain the standard fallback, so exact geometry can depend on the font.
40
42
 
41
43
  ## Fill the viewport for small Excel sheets
42
44
 
@@ -50,7 +52,7 @@ const options = {
50
52
  }
51
53
  ```
52
54
 
53
- This changes only the display: workbook data, used range, original-file downloads/exports, search results and content counts remain unchanged. CSV / TSV / ODS / Numbers ignore this option. Omitting it or setting it to `false` preserves the existing behavior.
55
+ This changes only the display: workbook data, used range, original-file downloads/exports, search results and content counts remain unchanged.
54
56
 
55
57
  ## Offline Assets
56
58
 
package/README.zh-CN.md CHANGED
@@ -37,6 +37,8 @@ const options = {
37
37
  - 支持多 sheet、横向滚动标签栏、合并单元格、列宽/行高、边框、填充、对齐、文本颜色、Office 365 / WPS 单元格内嵌图片、workbook drawing 图片、图片双击大图预览、统一缩放 provider 和可选表头拖拽调整列宽。
38
38
  - XLSX drawing 中的 TIFF 图片会按需加载 MIT 许可的 UTIF.js,在浏览器内转换为 PNG;普通表格不会加载 TIFF 解码器。
39
39
  - 表格使用虚拟渲染,适合交互预览;完整打印按钮通常由上层能力判断隐藏,避免只打印当前视口。
40
+ - XLSX 保留文件保存的默认列宽、显式列宽和以磅记录的行高;CSV/TSV 继续按内容调整列宽,大文本解析避免重复创建完整 UTF-8 字节数组。
41
+ - 列宽单位以工作簿 Normal 样式为基准。宋体、新宋体的数字宽度先从磅转换为像素,再进行取整;尚未测定的自定义字体沿用标准回退,实际尺寸可能受字体影响。
40
42
 
41
43
  ## 小内容 Excel 填满视口
42
44
 
@@ -50,7 +52,7 @@ const options = {
50
52
  }
51
53
  ```
52
54
 
53
- 补充部分只用于显示,不改变工作簿数据、used-range、原文件下载/导出、搜索结果或内容统计。CSV / TSV / ODS / Numbers 等格式忽略此属性;不传或设为 `false` 保持原有行为。
55
+ 补充部分只用于显示,不改变工作簿数据、used-range、原文件下载/导出、搜索结果或内容统计。
54
56
 
55
57
  ## 离线资产
56
58
 
@@ -24,6 +24,9 @@ const svgText = (documentRef, value, x, y, options = {}) => {
24
24
  text.textContent = value;
25
25
  return text;
26
26
  };
27
+ // The fixed plot coordinate system is letterboxed into the authored chart box.
28
+ // Compensate font units once for that intrinsic scale; sheet zoom is still
29
+ // applied by the containing renderer, so user zoom never gets cancelled out.
27
30
  const axisFontSize = (chart, size, fallback) => {
28
31
  const scale = Math.min(chart.width / 640, chart.height / 360);
29
32
  return size !== undefined && Number.isFinite(size) && size > 0 && Number.isFinite(scale) && scale > 0
@@ -395,6 +398,7 @@ const polarPoint = (cx, cy, radius, angle) => {
395
398
  };
396
399
  };
397
400
  const pieSlicePath = (cx, cy, outerRadius, innerRadius, startAngle, endAngle) => {
401
+ // A single SVG arc with identical endpoints is empty, not a full circle.
398
402
  if (endAngle - startAngle >= 360 - 1e-7) {
399
403
  const a = polarPoint(cx, cy, outerRadius, startAngle);
400
404
  const b = polarPoint(cx, cy, outerRadius, startAngle + 180);
@@ -449,6 +453,7 @@ const drawLegend = (documentRef, svg, chart) => {
449
453
  }
450
454
  const right = chart.legendPosition === 'right';
451
455
  const categorySeries = chart.type === 'pie' || chart.type === 'doughnut' ? chart.series[0] : undefined;
456
+ // Build only visible entries when a pie has a large category cache.
452
457
  const entries = chart.type === 'pie' || chart.type === 'doughnut'
453
458
  ? ((categorySeries === null || categorySeries === void 0 ? void 0 : categorySeries.values) || []).slice(0, MAX_LEGEND_ITEMS).map((_, index) => ({
454
459
  ...categorySeries,
@@ -1,2 +1,6 @@
1
1
  export declare const MAX_TRANSFERRED_LINE_CHART_POINTS = 4096;
2
+ /** Keep absent points as explicit separators through both transfer and SVG
3
+ * sampling. Otherwise an omitted gap becomes an invented connecting segment.
4
+ * Reserve at most one separator per retained interval, keeping a strict budget.
5
+ */
2
6
  export declare const extremaPointIndexes: (values: number[], maxPoints: number, spanBlankIndexes?: number[]) => number[];
@@ -36,6 +36,10 @@ const sampleExtrema = (values, maxPoints) => {
36
36
  result.push(values.length - 1);
37
37
  return Array.from(new Set(result));
38
38
  };
39
+ /** Keep absent points as explicit separators through both transfer and SVG
40
+ * sampling. Otherwise an omitted gap becomes an invented connecting segment.
41
+ * Reserve at most one separator per retained interval, keeping a strict budget.
42
+ */
39
43
  export const extremaPointIndexes = (values, maxPoints, spanBlankIndexes = []) => {
40
44
  const limit = Math.max(2, Number.isFinite(maxPoints) ? Math.floor(maxPoints) : 2);
41
45
  if (values.length <= limit)
@@ -46,6 +50,8 @@ export const extremaPointIndexes = (values, maxPoints, spanBlankIndexes = []) =>
46
50
  const spanning = new Set(spanBlankIndexes);
47
51
  const hardGap = (index) => !Number.isFinite(values[index]) && !spanning.has(index);
48
52
  if (limit === 2) {
53
+ // There is no room for both endpoints and a separator. Prefer dropping one
54
+ // endpoint over inventing a connecting line across an absent interval.
49
55
  const gap = values.findIndex((_, index) => hardGap(index));
50
56
  return gap > 0 && gap < values.length - 1 ? [0, gap] : [0, values.length - 1];
51
57
  }
@@ -10,11 +10,13 @@ type Options = {
10
10
  jump: (range: FileViewerSpreadsheetRange) => void;
11
11
  clearJump: () => void;
12
12
  };
13
+ /** Own requests from registration through parsing, virtual-window loading and paint. */
13
14
  export declare const createSpreadsheetRangeNavigation: (options: Options) => {
14
15
  provider: FileViewerViewStateProvider;
15
16
  cancel: (result?: "cancelled" | "failed" | "disposed") => void;
16
17
  notify: (action: FileViewerViewStateChange["action"], source?: FileViewerViewStateChange["source"], notify?: boolean) => void;
17
18
  isPending: () => boolean;
19
+ /** Called after the target virtual window loads, before drawing the highlight. */
18
20
  prepare(totalRows: number, totalCols: number): (() => void) | null;
19
21
  contains(sheetId: number, row: number, col: number): boolean;
20
22
  };
@@ -14,6 +14,7 @@ const cloneState = (state) => ({
14
14
  range: state.spreadsheet.range ? { ...state.spreadsheet.range } : undefined,
15
15
  } : undefined,
16
16
  });
17
+ /** Own requests from registration through parsing, virtual-window loading and paint. */
17
18
  export const createSpreadsheetRangeNavigation = (options) => {
18
19
  let stopped;
19
20
  let status = 'idle';
@@ -52,6 +53,7 @@ export const createSpreadsheetRangeNavigation = (options) => {
52
53
  }
53
54
  };
54
55
  const cancel = (result = 'cancelled') => {
56
+ // Disposal is terminal, including when a late parser rejection arrives.
55
57
  if (stopped === 'disposed')
56
58
  return;
57
59
  const hadHighlight = !!highlighted;
@@ -66,6 +68,7 @@ export const createSpreadsheetRangeNavigation = (options) => {
66
68
  if (result === 'disposed')
67
69
  listeners.clear();
68
70
  };
71
+ // Consume failure even when no API request was made before parsing failed.
69
72
  void options.ready.catch(() => { if (!stopped)
70
73
  cancel('failed'); });
71
74
  const provider = {
@@ -140,6 +143,7 @@ export const createSpreadsheetRangeNavigation = (options) => {
140
143
  return {
141
144
  provider, cancel, notify: emit,
142
145
  isPending: () => !!(pending === null || pending === void 0 ? void 0 : pending.range),
146
+ /** Called after the target virtual window loads, before drawing the highlight. */
143
147
  prepare(totalRows, totalCols) {
144
148
  const request = pending;
145
149
  if (!(request === null || request === void 0 ? void 0 : request.range))
@@ -55,6 +55,7 @@ export interface VirtualSheetState {
55
55
  mergeStartMap: Map<string, CellMerge>;
56
56
  mergeCoveredMap: Map<string, true>;
57
57
  rowHeightCache: Map<number, number>;
58
+ /** Unscaled user sizes take precedence over asynchronously loaded metrics. */
58
59
  rowHeightOverrides: Map<number, number>;
59
60
  windowRows: Map<number, number[]>;
60
61
  windowCells: Map<number, string[]>;
@@ -65,6 +65,8 @@ export const getWindowStart = (row = 0, totalRows = 0) => {
65
65
  const start = Math.floor(Math.max(row, 0) / WINDOW_SIZE) * WINDOW_SIZE;
66
66
  return clampWindowStart(start, totalRows);
67
67
  };
68
+ // 视口周边始终保留一小圈热窗口,滚轮滚动和拖动滚动条都可以直接命中缓存,
69
+ // 避免每次跳转都同步等待 worker 回包。
68
70
  export const collectWindowStarts = ({ startRow, endRow, direction, totalRows, far = false }) => {
69
71
  const starts = new Set();
70
72
  const firstWindow = getWindowStart(startRow, totalRows);
@@ -169,7 +169,7 @@ export const buildFont = (style) => {
169
169
  return [
170
170
  style.fontStyle || 'normal',
171
171
  normalizedWeight,
172
- `${Number.parseInt(style.fontSize, 10) || TABLE_FONT_SIZE}px`,
172
+ `${Number.parseFloat(style.fontSize) || TABLE_FONT_SIZE}px`,
173
173
  normalizeFontFamily(style.fontFamily)
174
174
  ].join(' ');
175
175
  };
@@ -235,9 +235,12 @@ export const getRowHeight = (heights, index, fallback) => {
235
235
  }
236
236
  return (_a = heights === null || heights === void 0 ? void 0 : heights[index]) !== null && _a !== void 0 ? _a : fallback;
237
237
  };
238
+ // Excel 已经给出了行高时,预览层不再二次猜测。
239
+ // 只有完全缺失时才回退到默认行高,同时给极小值留一个最小可渲染下限。
238
240
  export const normalizeRowHeight = (height, fallback) => {
239
241
  if (typeof height === 'number' && Number.isFinite(height)) {
240
242
  if (height <= 0) {
243
+ // e-virt-table 内部用 item._height || CELL_HEIGHT,0 会被误判为未设置。
241
244
  return HIDDEN_ROW_HEIGHT;
242
245
  }
243
246
  return Math.max(Math.ceil(height), MIN_RENDERABLE_ROW_HEIGHT);
@@ -254,6 +257,8 @@ const isPlainTextCell = (value) => {
254
257
  }
255
258
  return !/^\d+([./:-]\d+)*$/.test(text);
256
259
  };
260
+ // 普通明细表通常会把第一行当成字段表头,而报表类工作表往往需要保留原始 Excel 行号。
261
+ // 这里只在“首行像简单字段头且没有合并单元格”时,才给左侧序号做 1 行偏移。
257
262
  export const detectIndexOffset = (ws) => {
258
263
  const meta = ws.meta;
259
264
  const rows = ws.data || [];
@@ -340,6 +345,7 @@ const scaleColumn = (column, zoomScale) => {
340
345
  }
341
346
  return nextColumn;
342
347
  };
348
+ // Excel 预览优先忠实还原原始列宽,不再为了“铺满容器”二次拉伸列宽。
343
349
  export const getDisplayColumns = (columns, zoomScale = 1) => {
344
350
  const normalizedScale = normalizeZoomScale(zoomScale);
345
351
  if (normalizedScale === 1) {
@@ -425,6 +431,7 @@ const shouldRenderTextInOverlay = (style, column) => {
425
431
  if (!hasTextLayout(style)) {
426
432
  return false;
427
433
  }
434
+ // e-virt-table 的列级 align 可以交给 canvas;只有单元格级布局差异才用 DOM 覆盖层补齐。
428
435
  return !!((style === null || style === void 0 ? void 0 : style.wrapText) ||
429
436
  (style === null || style === void 0 ? void 0 : style.shrinkToFit) ||
430
437
  ((style === null || style === void 0 ? void 0 : style.horizontalAlign) && style.horizontalAlign !== ((column === null || column === void 0 ? void 0 : column.align) || 'left')) ||
@@ -547,7 +554,7 @@ const getExcelOverflowLayout = (virtualState, row, rowIndex, dataColIndex, colum
547
554
  if (!ownWidth) {
548
555
  return undefined;
549
556
  }
550
- const font = (style === null || style === void 0 ? void 0 : style.font) || BODY_FONT;
557
+ const font = (style === null || style === void 0 ? void 0 : style.font) || getBodyFont(zoomScale);
551
558
  const measuredWidth = Math.ceil(measureTextWidth(text, font, scaleNumber(CELL_PADDING, zoomScale), documentRef));
552
559
  if (measuredWidth <= ownWidth) {
553
560
  return undefined;
@@ -775,6 +782,8 @@ const applyOverflowLayout = (text, overflowLayout) => {
775
782
  textOverflow: 'clip'
776
783
  });
777
784
  };
785
+ // e-virt-table 的普通样式接口不支持 Excel 式四边边框和单元格级换行/垂直对齐,
786
+ // 这里借助官方的 BODY_CELL_RENDER_METHOD,只在可视区补轻量 DOM 覆盖层。
778
787
  const renderCellOverlay = (cellEl, borderStyle, textStyle, textValue, renderText, overflowLayout, zoomScale) => {
779
788
  const documentRef = cellEl.ownerDocument;
780
789
  cellEl.replaceChildren();
@@ -1036,6 +1045,8 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
1036
1045
  RESIZE_ROW_LINE_COLOR: EXCEL_GREEN,
1037
1046
  RESIZE_ROW_MIN_HEIGHT: scaleNumber(RESIZABLE_ROW_MIN_HEIGHT, normalizedScale),
1038
1047
  ENABLE_KEYBOARD: true,
1048
+ // The table finder only indexes loaded rows and competes with the viewer's
1049
+ // workbook-wide search shortcut. Keep one search owner for all integrations.
1039
1050
  ENABLE_FINDER: false,
1040
1051
  ENABLE_COPY: true,
1041
1052
  BEFORE_COPY_METHOD: copySelection
@@ -1044,6 +1055,7 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
1044
1055
  return undefined;
1045
1056
  }
1046
1057
  : undefined,
1058
+ // 预览态只开放“拖动扩选”的交互,不允许真正写回单元格内容。
1047
1059
  BEFORE_AUTOFILL_DATA_METHOD: () => [],
1048
1060
  SPAN_METHOD: spanMethod,
1049
1061
  HEADER_CELL_STYLE_METHOD: headerStyleMethod,
@@ -1,6 +1,7 @@
1
1
  import type { Column } from 'e-virt-table';
2
2
  import { type VirtualRow, type VirtualSheetState } from './state.js';
3
3
  export declare const shouldFillSpreadsheetViewport: (enabled: boolean | undefined, type?: string) => boolean;
4
+ /** Display-only padding. The parser's dimensions, rows and columns stay authoritative. */
4
5
  export declare class SpreadsheetViewportFill {
5
6
  private sourceRows?;
6
7
  private rows;
@@ -12,6 +12,7 @@ const columnLabel = (index) => {
12
12
  }
13
13
  return label;
14
14
  };
15
+ /** Display-only padding. The parser's dimensions, rows and columns stay authoritative. */
15
16
  export class SpreadsheetViewportFill {
16
17
  constructor() {
17
18
  this.rows = [];
@@ -51,6 +52,7 @@ export class SpreadsheetViewportFill {
51
52
  verticalAlign: 'middle',
52
53
  }))) : state.columns;
53
54
  }
55
+ // Blank rows use default metrics even when the host allows resizing data rows.
54
56
  for (let index = state.totalRows; index < this.rows.length; index += 1)
55
57
  this.rows[index]._height = rowHeight;
56
58
  return { rows: this.rows, columns: this.columns };
@@ -43,10 +43,9 @@ const toFiniteNumber = (value) => {
43
43
  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
44
44
  };
45
45
  const getDefaultColumnWidth = () => {
46
- var _a;
47
- const converter = utils.col_width_to_px;
48
- const value = typeof converter === 'function' ? converter(EXCEL_DEFAULT_COLUMN_WIDTH) : undefined;
49
- return Math.ceil((_a = toFiniteNumber(value)) !== null && _a !== void 0 ? _a : 64);
46
+ // Excel's displayed default is 8.43 characters plus five pixels of padding,
47
+ // not an already encoded OOXML <col width> value.
48
+ return Math.floor(EXCEL_DEFAULT_COLUMN_WIDTH * 7 + 5);
50
49
  };
51
50
  const getDefaultRowHeight = () => {
52
51
  var _a;
@@ -80,13 +79,18 @@ export const formatCellValue = (cell) => {
80
79
  }
81
80
  return `${cell.v}`;
82
81
  };
83
- const getColumnPixelWidth = (column) => {
82
+ const getColumnPixelWidth = (column, maximumDigitWidth = 7) => {
84
83
  if (!column) {
85
84
  return undefined;
86
85
  }
87
86
  if (column.hidden) {
88
87
  return 0;
89
88
  }
89
+ const storedWidth = toFiniteNumber(column.width);
90
+ if (maximumDigitWidth !== 7 && storedWidth !== undefined && storedWidth >= 0) {
91
+ return Math.trunc(((256 * storedWidth + Math.trunc(128 / maximumDigitWidth)) / 256) * maximumDigitWidth);
92
+ }
93
+ // styled-exceljs 在 browserPixels 模式下会优先输出 wpx,这是最接近浏览器渲染的列宽。
90
94
  const wpx = toFiniteNumber(column.wpx);
91
95
  if (wpx !== undefined && wpx >= 0) {
92
96
  return Math.ceil(wpx);
@@ -141,16 +145,18 @@ const getRowPixelHeight = (rowMeta) => {
141
145
  if (rowMeta.hidden) {
142
146
  return 0;
143
147
  }
144
- const hpx = toFiniteNumber(rowMeta.hpx);
145
- if (hpx !== undefined && hpx >= 0) {
146
- return Math.ceil(hpx);
147
- }
148
+ // The parser retains OOXML points in hpt, but its legacy hpx conversion
149
+ // uses 96/96. Prefer the authoritative points and convert to CSS pixels once.
148
150
  const hpt = toFiniteNumber(rowMeta.hpt);
149
151
  if (hpt !== undefined && hpt >= 0) {
150
152
  const converter = utils.row_height_to_px;
151
153
  const converted = typeof converter === 'function' ? toFiniteNumber(converter(hpt)) : undefined;
152
154
  return Math.ceil(converted !== null && converted !== void 0 ? converted : hpt * 96 / 72);
153
155
  }
156
+ const hpx = toFiniteNumber(rowMeta.hpx);
157
+ if (hpx !== undefined && hpx >= 0) {
158
+ return Math.ceil(hpx);
159
+ }
154
160
  return undefined;
155
161
  };
156
162
  const normalizeHorizontalAlign = (value) => {
@@ -229,6 +235,8 @@ const isAutomaticPaletteColor = (color) => {
229
235
  return indexed === 32767;
230
236
  };
231
237
  const normalizeFontColor = (color) => {
238
+ // BIFF/XLS 会把“自动字体色”解析成 indexed 32767,部分文件还会附带
239
+ // FFFFFF 的 rgb 值。Excel 实际显示为默认黑色,不能当成显式白色。
232
240
  if (isAutomaticPaletteColor(color)) {
233
241
  return EXCEL_DEFAULT_TEXT_COLOR;
234
242
  }
@@ -312,9 +320,10 @@ const getCellStyle = (cellStyle) => {
312
320
  if (font.bold || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.bold)) {
313
321
  style.fontWeight = 'bold';
314
322
  }
315
- const fontSize = font.sz || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.sz);
316
- if (fontSize) {
317
- style.fontSize = `${fontSize}px`;
323
+ const fontSize = Number(font.sz || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.sz));
324
+ if (Number.isFinite(fontSize) && fontSize > 0) {
325
+ // Excel 字号以 pt 存储;模型统一输出 CSS px,视图层再单独应用缩放。
326
+ style.fontSize = `${fontSize * 96 / 72}px`;
318
327
  }
319
328
  const fontName = font.name || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.name);
320
329
  if (fontName) {
@@ -366,7 +375,14 @@ class SheetJsModel {
366
375
  return this._ws;
367
376
  }
368
377
  get defaults() {
369
- return SheetJsModel.defaults;
378
+ const layout = this.ws['!fileViewerLayout'];
379
+ if (!layout)
380
+ return SheetJsModel.defaults;
381
+ const columnWidth = layout.columnWidth === undefined ? undefined : getColumnPixelWidth({ width: layout.columnWidth }, layout.maximumDigitWidth);
382
+ return {
383
+ colWidth: columnWidth !== null && columnWidth !== void 0 ? columnWidth : SheetJsModel.defaults.colWidth,
384
+ rowHeight: layout.rowHeightPt === undefined ? SheetJsModel.defaults.rowHeight : Math.ceil(layout.rowHeightPt * 96 / 72)
385
+ };
370
386
  }
371
387
  get data() {
372
388
  var _a;
@@ -615,6 +631,7 @@ class SheetJsModel {
615
631
  }
616
632
  return heights.length ? heights : rowHeight;
617
633
  }
634
+ // 整表行高必须按绝对行号下发,否则拖动滚动条时隐藏行和特殊行高会造成高度跳变。
618
635
  getAllRowHeights() {
619
636
  const { '!rows': rows = [] } = this.ws;
620
637
  const heights = [];
@@ -638,6 +655,8 @@ class SheetJsModel {
638
655
  const sampleRanges = this.getAutoFitSampleRanges();
639
656
  const fittedColumns = [];
640
657
  for (const range of sampleRanges) {
658
+ // 自动列宽只作为缺失列宽的兜底。合并标题和 Excel 溢出文本不应该反向撑开基础列宽。
659
+ // 大表只抽样固定数量的单元格,避免为了首屏列宽扫描整张工作表。
641
660
  const measuredColumns = autoFitColumns(this.ws, {
642
661
  range,
643
662
  set: false,
@@ -680,9 +699,13 @@ class SheetJsModel {
680
699
  if (hasColumnWidth(sourceColumn)) {
681
700
  return sourceColumn;
682
701
  }
683
- if (this.hasAnchoredObjects) {
702
+ // A drawing anchor is measured against the workbook's stored/default
703
+ // column geometry. Auto-fitting blank columns to 24px changes that
704
+ // coordinate system and makes two-cell images visibly smaller than Excel.
705
+ if (this.hasAnchoredObjects || this.ws['!fileViewerLayout']) {
684
706
  return sourceColumn;
685
707
  }
708
+ // 没有显式列宽时,再使用 styled-exceljs 的内容测量兜底,避免报表类标题污染原始宽度。
686
709
  return ((_a = this.autoFitColumns) === null || _a === void 0 ? void 0 : _a[colIndex]) || sourceColumn;
687
710
  }
688
711
  get hasAnchoredObjects() {
@@ -691,11 +714,12 @@ class SheetJsModel {
691
714
  return !!((_a = drawings === null || drawings === void 0 ? void 0 : drawings.images) === null || _a === void 0 ? void 0 : _a.length) || !!this._charts.length || !!this._cellImages.length;
692
715
  }
693
716
  getColWidths() {
717
+ var _a;
694
718
  const { colWidth } = this.defaults;
695
719
  const { '!cols': sourceCols = [] } = this.ws;
696
720
  const widths = [];
697
721
  for (let colIndex = 0; colIndex < this.totalCols; colIndex += 1) {
698
- const width = getColumnPixelWidth(this.getColumnMeta(sourceCols, colIndex));
722
+ const width = getColumnPixelWidth(this.getColumnMeta(sourceCols, colIndex), (_a = this.ws['!fileViewerLayout']) === null || _a === void 0 ? void 0 : _a.maximumDigitWidth);
699
723
  if (width !== undefined) {
700
724
  widths[colIndex] = width;
701
725
  }
@@ -1,10 +1,12 @@
1
1
  import { DOMParser } from '@xmldom/xmldom';
2
2
  import JSZip from 'jszip';
3
+ import { readStoredSheetLayout, readWorkbookDigitWidth } from './sheetLayout.js';
3
4
  import { extremaPointIndexes, MAX_TRANSFERRED_LINE_CHART_POINTS } from '../../chartSampling.js';
4
5
  const CHART_RELATIONSHIP_SUFFIX = '/chart';
5
6
  const DRAWING_RELATIONSHIP_SUFFIX = '/drawing';
6
7
  const WORKSHEET_RELATIONSHIP_SUFFIX = '/worksheet';
7
8
  const EMUS_PER_CSS_PIXEL = 9525;
9
+ // Bound cache indices and formula expansion before allocating producer-controlled arrays.
8
10
  const MAX_CHART_POINTS = 1048576;
9
11
  const CHART_TYPE_MAP = {
10
12
  areaChart: 'area',
@@ -115,6 +117,9 @@ const relationshipPartPath = (sourcePart) => {
115
117
  return `${directory ? `${directory}/` : ''}_rels/${filename}.rels`;
116
118
  };
117
119
  const parseXml = (xml) => {
120
+ // Some valid Office producers prefix relationship parts with a UTF-8 BOM.
121
+ // XML declarations must otherwise be the first character, and xmldom reports
122
+ // the BOM as content outside the root element before aborting chart parsing.
118
123
  return new DOMParser().parseFromString(xml.replace(/^[\uFEFF\s]+/, ''), 'application/xml');
119
124
  };
120
125
  export const loadXml = async (zip, path) => {
@@ -246,6 +251,8 @@ const parsePointValues = (element, workbook, formatted = true) => {
246
251
  if (!element) {
247
252
  return [];
248
253
  }
254
+ // Cache point idx is a logical source position, not the point's XML order.
255
+ // Select one cache/level; flattening nested caches mixes category hierarchies.
249
256
  const literal = firstChildByLocal(element, 'strLit') || firstChildByLocal(element, 'numLit');
250
257
  const reference = firstChildByLocal(element, 'strRef') || firstChildByLocal(element, 'numRef');
251
258
  const multiLevel = firstChildByLocal(firstChildByLocal(element, 'multiLvlStrRef'), 'multiLvlStrCache');
@@ -271,6 +278,9 @@ const parsePointValues = (element, workbook, formatted = true) => {
271
278
  const values = Array(count).fill('');
272
279
  for (const point of entries)
273
280
  values[point.index] = point.value;
281
+ // A declared domain with missing points is an intentional sparse cache.
282
+ // A zero-length reference cache supplies no domain; Office producers use
283
+ // it as a placeholder until Excel recalculates the worksheet formula.
274
284
  if (count || literal || !reference)
275
285
  return values;
276
286
  }
@@ -348,6 +358,8 @@ const parseSeries = (chartNode, workbook, blankMode = 'gap') => {
348
358
  spanBlankIndexes.push(pointIndex);
349
359
  return blankMode === 'zero' ? 0 : Number.NaN;
350
360
  }
361
+ // Empty cells and error values are not zero. Keep an error as a hard gap,
362
+ // even when blank cells are explicitly spanned or plotted as zero.
351
363
  const number = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(raw) ? Number(raw) : NaN;
352
364
  return Number.isFinite(number) ? number : Number.NaN;
353
365
  });
@@ -380,6 +392,7 @@ const parseSeries = (chartNode, workbook, blankMode = 'gap') => {
380
392
  };
381
393
  });
382
394
  };
395
+ /** DrawingML font sizes are hundredths of a point, not SVG viewport units. */
383
396
  const parseAxisFontSize = (axis, chartSpace) => {
384
397
  var _a;
385
398
  const size = (node) => {
@@ -469,6 +482,7 @@ const parseDrawingCharts = async (zip, drawingPart, workbook) => {
469
482
  return charts.filter((chart) => chart !== null);
470
483
  };
471
484
  export const parseSpreadsheetCharts = async (data, workbook) => {
485
+ var _a;
472
486
  const zip = await JSZip.loadAsync(data);
473
487
  const workbookPart = 'xl/workbook.xml';
474
488
  const [workbookDocument, workbookRelationships] = await Promise.all([
@@ -479,12 +493,28 @@ export const parseSpreadsheetCharts = async (data, workbook) => {
479
493
  if (!workbookDocument) {
480
494
  return result;
481
495
  }
496
+ const maximumDigitWidth = readWorkbookDigitWidth(workbook);
482
497
  for (const sheet of elementsByLocal(workbookDocument.documentElement, 'sheet')) {
483
498
  const name = sheet.getAttribute('name') || '';
484
499
  const worksheetRelationship = relationById(workbookRelationships, relationshipId(sheet));
485
500
  if (!name || !(worksheetRelationship === null || worksheetRelationship === void 0 ? void 0 : worksheetRelationship.type.endsWith(WORKSHEET_RELATIONSHIP_SUFFIX))) {
486
501
  continue;
487
502
  }
503
+ // A missing <col> uses the worksheet's stored/default geometry, rather
504
+ // than content auto-fit. Keep this metadata even when there are no charts.
505
+ const worksheet = (_a = workbook === null || workbook === void 0 ? void 0 : workbook.Sheets) === null || _a === void 0 ? void 0 : _a[name];
506
+ if (worksheet) {
507
+ worksheet['!fileViewerLayout'] = {};
508
+ worksheet['!fileViewerLayout'] = {
509
+ ...await readStoredSheetLayout(zip, worksheetRelationship.target),
510
+ maximumDigitWidth
511
+ };
512
+ }
513
+ // A worksheet can expand to hundreds of megabytes even when the drawing
514
+ // relationship part is only a few hundred bytes. Loading sheetN.xml as a
515
+ // string here duplicates the cell parser's work and can exceed V8's string
516
+ // limit before chart parsing starts. Drawing relationships already carry
517
+ // the typed targets needed by the chart parser, so discover them directly.
488
518
  const worksheetRelationships = await loadRelationships(zip, worksheetRelationship.target);
489
519
  const drawingParts = Array.from(new Set(worksheetRelationships
490
520
  .filter((relationship) => relationship.type.endsWith(DRAWING_RELATIONSHIP_SUFFIX))
@@ -1,16 +1,17 @@
1
1
  import tinycolor from 'tinycolor2';
2
2
  export const indexedColors = [
3
- 'FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF', 'FFFFFF00', 'FFFF00FF', 'FF00FFFF',
4
- 'FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF', 'FFFFFF00', 'FFFF00FF', 'FF00FFFF',
5
- 'FF800000', 'FF008000', 'FF000080', 'FF808000', 'FF800080', 'FF008080', 'FFC0C0C0', 'FF808080',
6
- 'FF9999FF', 'FF993366', 'FFFFFFCC', 'FFCCFFFF', 'FF660066', 'FFFF8080', 'FF0066CC', 'FFCCCCFF',
7
- 'FF000080', 'FFFF00FF', 'FFFFFF00', 'FF00FFFF', 'FF800080', 'FF800000', 'FF008080', 'FF0000FF',
8
- 'FF00CCFF', 'FFCCFFFF', 'FFCCFFCC', 'FFFFFF99', 'FF99CCFF', 'FFFF99CC', 'FFCC99FF', 'FFFFCC99',
9
- 'FF3366FF', 'FF33CCCC', 'FF99CC00', 'FFFFCC00', 'FFFF9900', 'FFFF6600', 'FF666699', 'FF969696',
10
- 'FF003366', 'FF339966', 'FF003300', 'FF333300', 'FF993300', 'FF993366', 'FF333399', 'FF333333'
3
+ 'FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF', 'FFFFFF00', 'FFFF00FF', 'FF00FFFF', // 0-7
4
+ 'FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF', 'FFFFFF00', 'FFFF00FF', 'FF00FFFF', // 8-15
5
+ 'FF800000', 'FF008000', 'FF000080', 'FF808000', 'FF800080', 'FF008080', 'FFC0C0C0', 'FF808080', // 16-23
6
+ 'FF9999FF', 'FF993366', 'FFFFFFCC', 'FFCCFFFF', 'FF660066', 'FFFF8080', 'FF0066CC', 'FFCCCCFF', // 24-31
7
+ 'FF000080', 'FFFF00FF', 'FFFFFF00', 'FF00FFFF', 'FF800080', 'FF800000', 'FF008080', 'FF0000FF', // 32-39
8
+ 'FF00CCFF', 'FFCCFFFF', 'FFCCFFCC', 'FFFFFF99', 'FF99CCFF', 'FFFF99CC', 'FFCC99FF', 'FFFFCC99', // 40-47
9
+ 'FF3366FF', 'FF33CCCC', 'FF99CC00', 'FFFFCC00', 'FFFF9900', 'FFFF6600', 'FF666699', 'FF969696', // 48-55
10
+ 'FF003366', 'FF339966', 'FF003300', 'FF333300', 'FF993300', 'FF993366', 'FF333399', 'FF333333' // 56-63
11
11
  ];
12
12
  const HLSMAX = 240;
13
13
  const RGBMAX = 0xFF;
14
+ // Excel 主题色的 tint 计算使用微软 HLS 取值范围,和浏览器 HSL 不是同一套刻度。
14
15
  function rgb2hls(r, g, b) {
15
16
  const maxc = Math.max(r, g, b);
16
17
  const minc = Math.min(r, g, b);
@@ -62,6 +63,7 @@ function tintLuminance(tint, lum) {
62
63
  }
63
64
  return Math.round(lum * (1.0 - tint) + (HLSMAX - HLSMAX * (1.0 - tint)));
64
65
  }
66
+ // 根据主题原始色和 tint 还原 Excel 实际显示色。
65
67
  export function getTintColor(hex, tint) {
66
68
  if (!hex) {
67
69
  return hex;
@@ -79,6 +79,7 @@ class FormulaParser {
79
79
  };
80
80
  while (((_a = precedence[this.current().kind]) !== null && _a !== void 0 ? _a : -1) >= minimum) {
81
81
  const op = this.tokens[this.index++].kind;
82
+ // Excel exponentiation is left associative.
82
83
  left = { kind: 'binary', op, left, right: this.expression(precedence[op] + 1) };
83
84
  }
84
85
  this.depth--;
@@ -162,6 +163,8 @@ const numeric = (value) => {
162
163
  return 0;
163
164
  if (typeof value === 'boolean')
164
165
  return value ? 1 : 0;
166
+ // Blank cells use null. Empty strings and JavaScript-only hexadecimal text
167
+ // are not Excel arithmetic numbers and must not silently become 0 or 16.
165
168
  if (typeof value === 'string' &&
166
169
  !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?$/.test(value.trim()))
167
170
  return unavailable();
@@ -289,6 +292,8 @@ export function recoverUncachedFormulaValues(workbook) {
289
292
  if (node.op === '&')
290
293
  return textValue(left) + textValue(right);
291
294
  if (['=', '<>', '<', '>', '<=', '>='].includes(node.op)) {
295
+ // Excel compares text without case sensitivity. Different value types
296
+ // are ordered number < text < logical; empty cells take the other type.
292
297
  const normalize = (value, other) => value === null
293
298
  ? typeof other === 'string'
294
299
  ? ''
@@ -316,6 +321,7 @@ export function recoverUncachedFormulaValues(workbook) {
316
321
  const a = numeric(left), b = numeric(right);
317
322
  if (node.op === '/' && b === 0)
318
323
  return unavailable();
324
+ // Office POWER(0,0) is an error, unlike JavaScript's finite result1.
319
325
  if (node.op === '^' && a === 0 && b === 0)
320
326
  return unavailable();
321
327
  const value = node.op === '+'
@@ -385,6 +391,7 @@ export function recoverUncachedFormulaValues(workbook) {
385
391
  readCell(name, row, col, 0);
386
392
  }
387
393
  catch {
394
+ /* keep the original formula visible */
388
395
  }
389
396
  }
390
397
  for (const { cells } of sheets.values())
@@ -395,11 +402,13 @@ export function recoverUncachedFormulaValues(workbook) {
395
402
  const value = (_a = results.get(cell)) !== null && _a !== void 0 ? _a : 0;
396
403
  cell.v = value;
397
404
  cell.t = typeof value === 'boolean' ? 'b' : typeof value === 'string' ? 's' : 'n';
405
+ // The parser may have produced w="0" for an empty cached value.
398
406
  delete cell.w;
399
407
  try {
400
408
  cell.w = utils.format_cell(cell);
401
409
  }
402
410
  catch {
411
+ /* plain value is still available */
403
412
  }
404
413
  calculated++;
405
414
  }
@@ -23,6 +23,7 @@ export interface SpreadsheetParserContext {
23
23
  cellImages: Record<string, SheetCellImage[]>;
24
24
  }
25
25
  export interface SpreadsheetWorkbookSource extends SpreadsheetTextSource {
26
+ /** Retain truly empty sheets only for the opt-in Excel viewport grid. */
26
27
  includeEmptySheets?: boolean;
27
28
  }
28
29
  export interface SpreadsheetWorkerRequest {