@file-viewer/renderer-spreadsheet 3.3.0 → 3.3.3

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
 
@@ -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
  };
@@ -547,7 +547,7 @@ const getExcelOverflowLayout = (virtualState, row, rowIndex, dataColIndex, colum
547
547
  if (!ownWidth) {
548
548
  return undefined;
549
549
  }
550
- const font = (style === null || style === void 0 ? void 0 : style.font) || BODY_FONT;
550
+ const font = (style === null || style === void 0 ? void 0 : style.font) || getBodyFont(zoomScale);
551
551
  const measuredWidth = Math.ceil(measureTextWidth(text, font, scaleNumber(CELL_PADDING, zoomScale), documentRef));
552
552
  if (measuredWidth <= ownWidth) {
553
553
  return undefined;
@@ -43,10 +43,7 @@ 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
+ return Math.floor(EXCEL_DEFAULT_COLUMN_WIDTH * 7 + 5);
50
47
  };
51
48
  const getDefaultRowHeight = () => {
52
49
  var _a;
@@ -80,13 +77,17 @@ export const formatCellValue = (cell) => {
80
77
  }
81
78
  return `${cell.v}`;
82
79
  };
83
- const getColumnPixelWidth = (column) => {
80
+ const getColumnPixelWidth = (column, maximumDigitWidth = 7) => {
84
81
  if (!column) {
85
82
  return undefined;
86
83
  }
87
84
  if (column.hidden) {
88
85
  return 0;
89
86
  }
87
+ const storedWidth = toFiniteNumber(column.width);
88
+ if (maximumDigitWidth !== 7 && storedWidth !== undefined && storedWidth >= 0) {
89
+ return Math.trunc(((256 * storedWidth + Math.trunc(128 / maximumDigitWidth)) / 256) * maximumDigitWidth);
90
+ }
90
91
  const wpx = toFiniteNumber(column.wpx);
91
92
  if (wpx !== undefined && wpx >= 0) {
92
93
  return Math.ceil(wpx);
@@ -141,16 +142,16 @@ const getRowPixelHeight = (rowMeta) => {
141
142
  if (rowMeta.hidden) {
142
143
  return 0;
143
144
  }
144
- const hpx = toFiniteNumber(rowMeta.hpx);
145
- if (hpx !== undefined && hpx >= 0) {
146
- return Math.ceil(hpx);
147
- }
148
145
  const hpt = toFiniteNumber(rowMeta.hpt);
149
146
  if (hpt !== undefined && hpt >= 0) {
150
147
  const converter = utils.row_height_to_px;
151
148
  const converted = typeof converter === 'function' ? toFiniteNumber(converter(hpt)) : undefined;
152
149
  return Math.ceil(converted !== null && converted !== void 0 ? converted : hpt * 96 / 72);
153
150
  }
151
+ const hpx = toFiniteNumber(rowMeta.hpx);
152
+ if (hpx !== undefined && hpx >= 0) {
153
+ return Math.ceil(hpx);
154
+ }
154
155
  return undefined;
155
156
  };
156
157
  const normalizeHorizontalAlign = (value) => {
@@ -312,9 +313,9 @@ const getCellStyle = (cellStyle) => {
312
313
  if (font.bold || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.bold)) {
313
314
  style.fontWeight = 'bold';
314
315
  }
315
- const fontSize = font.sz || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.sz);
316
- if (fontSize) {
317
- style.fontSize = `${fontSize}px`;
316
+ const fontSize = Number(font.sz || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.sz));
317
+ if (Number.isFinite(fontSize) && fontSize > 0) {
318
+ style.fontSize = `${fontSize * 96 / 72}px`;
318
319
  }
319
320
  const fontName = font.name || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.name);
320
321
  if (fontName) {
@@ -366,7 +367,14 @@ class SheetJsModel {
366
367
  return this._ws;
367
368
  }
368
369
  get defaults() {
369
- return SheetJsModel.defaults;
370
+ const layout = this.ws['!fileViewerLayout'];
371
+ if (!layout)
372
+ return SheetJsModel.defaults;
373
+ const columnWidth = layout.columnWidth === undefined ? undefined : getColumnPixelWidth({ width: layout.columnWidth }, layout.maximumDigitWidth);
374
+ return {
375
+ colWidth: columnWidth !== null && columnWidth !== void 0 ? columnWidth : SheetJsModel.defaults.colWidth,
376
+ rowHeight: layout.rowHeightPt === undefined ? SheetJsModel.defaults.rowHeight : Math.ceil(layout.rowHeightPt * 96 / 72)
377
+ };
370
378
  }
371
379
  get data() {
372
380
  var _a;
@@ -680,7 +688,7 @@ class SheetJsModel {
680
688
  if (hasColumnWidth(sourceColumn)) {
681
689
  return sourceColumn;
682
690
  }
683
- if (this.hasAnchoredObjects) {
691
+ if (this.hasAnchoredObjects || this.ws['!fileViewerLayout']) {
684
692
  return sourceColumn;
685
693
  }
686
694
  return ((_a = this.autoFitColumns) === null || _a === void 0 ? void 0 : _a[colIndex]) || sourceColumn;
@@ -691,11 +699,12 @@ class SheetJsModel {
691
699
  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
700
  }
693
701
  getColWidths() {
702
+ var _a;
694
703
  const { colWidth } = this.defaults;
695
704
  const { '!cols': sourceCols = [] } = this.ws;
696
705
  const widths = [];
697
706
  for (let colIndex = 0; colIndex < this.totalCols; colIndex += 1) {
698
- const width = getColumnPixelWidth(this.getColumnMeta(sourceCols, colIndex));
707
+ const width = getColumnPixelWidth(this.getColumnMeta(sourceCols, colIndex), (_a = this.ws['!fileViewerLayout']) === null || _a === void 0 ? void 0 : _a.maximumDigitWidth);
699
708
  if (width !== undefined) {
700
709
  widths[colIndex] = width;
701
710
  }
@@ -1,5 +1,6 @@
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';
@@ -469,6 +470,7 @@ const parseDrawingCharts = async (zip, drawingPart, workbook) => {
469
470
  return charts.filter((chart) => chart !== null);
470
471
  };
471
472
  export const parseSpreadsheetCharts = async (data, workbook) => {
473
+ var _a;
472
474
  const zip = await JSZip.loadAsync(data);
473
475
  const workbookPart = 'xl/workbook.xml';
474
476
  const [workbookDocument, workbookRelationships] = await Promise.all([
@@ -479,12 +481,21 @@ export const parseSpreadsheetCharts = async (data, workbook) => {
479
481
  if (!workbookDocument) {
480
482
  return result;
481
483
  }
484
+ const maximumDigitWidth = readWorkbookDigitWidth(workbook);
482
485
  for (const sheet of elementsByLocal(workbookDocument.documentElement, 'sheet')) {
483
486
  const name = sheet.getAttribute('name') || '';
484
487
  const worksheetRelationship = relationById(workbookRelationships, relationshipId(sheet));
485
488
  if (!name || !(worksheetRelationship === null || worksheetRelationship === void 0 ? void 0 : worksheetRelationship.type.endsWith(WORKSHEET_RELATIONSHIP_SUFFIX))) {
486
489
  continue;
487
490
  }
491
+ const worksheet = (_a = workbook === null || workbook === void 0 ? void 0 : workbook.Sheets) === null || _a === void 0 ? void 0 : _a[name];
492
+ if (worksheet) {
493
+ worksheet['!fileViewerLayout'] = {};
494
+ worksheet['!fileViewerLayout'] = {
495
+ ...await readStoredSheetLayout(zip, worksheetRelationship.target),
496
+ maximumDigitWidth
497
+ };
498
+ }
488
499
  const worksheetRelationships = await loadRelationships(zip, worksheetRelationship.target);
489
500
  const drawingParts = Array.from(new Set(worksheetRelationships
490
501
  .filter((relationship) => relationship.type.endsWith(DRAWING_RELATIONSHIP_SUFFIX))
@@ -12,6 +12,7 @@ const readOptions = {
12
12
  browserPixels: true,
13
13
  drawings: true,
14
14
  };
15
+ const prefersSheetJsTextSniff = (text) => /^[\s\uFEFF]*</.test(text);
15
16
  const isMergeValidationError = (error) => (error instanceof Error
16
17
  && typeof error.code === 'string'
17
18
  && /^E_MERGE_/.test(error.code));
@@ -78,7 +79,7 @@ const sanitizeToleratedMerges = (workbook) => {
78
79
  }
79
80
  };
80
81
  const readPreparedWorkbook = (input, validateMerges) => (input.kind === 'text'
81
- ? read(input.data, { ...readOptions, type: 'string', validateMerges })
82
+ ? read(input.data, { ...readOptions, type: prefersSheetJsTextSniff(input.data) ? 'string' : 'binary', validateMerges })
82
83
  : read(input.data, { ...readOptions, validateMerges }));
83
84
  const readWorkbookWithMergeRecovery = (input) => {
84
85
  try {
@@ -49,7 +49,7 @@ const parseColor = (element) => {
49
49
  };
50
50
  const parseFontSize = (element) => {
51
51
  const value = Number(element === null || element === void 0 ? void 0 : element.getAttribute('val'));
52
- return Number.isFinite(value) && value > 0 ? value : undefined;
52
+ return Number.isFinite(value) && value > 0 ? value * 96 / 72 : undefined;
53
53
  };
54
54
  const normalizeSymbolText = (text, fontFamily) => {
55
55
  if ((fontFamily === null || fontFamily === void 0 ? void 0 : fontFamily.trim().toLowerCase()) !== 'wingdings 2') {
@@ -0,0 +1,9 @@
1
+ import type JSZip from 'jszip';
2
+ import type { WorkBook } from 'styled-exceljs';
3
+ export interface StoredSheetLayout {
4
+ columnWidth?: number;
5
+ rowHeightPt?: number;
6
+ maximumDigitWidth?: number;
7
+ }
8
+ export declare const readWorkbookDigitWidth: (workbook?: WorkBook | null) => number;
9
+ export declare const readStoredSheetLayout: (zip: JSZip, part: string) => Promise<StoredSheetLayout>;
@@ -0,0 +1,60 @@
1
+ import { DOMParser } from '@xmldom/xmldom';
2
+ export const readWorkbookDigitWidth = (workbook) => {
3
+ var _a, _b, _c, _d, _e, _f, _g, _h;
4
+ const styles = workbook === null || workbook === void 0 ? void 0 : workbook.Styles;
5
+ const normal = (_b = (_a = styles === null || styles === void 0 ? void 0 : styles.CellStyles) === null || _a === void 0 ? void 0 : _a.find(style => style.builtinId === 0)) !== null && _b !== void 0 ? _b : (_c = styles === null || styles === void 0 ? void 0 : styles.CellStyles) === null || _c === void 0 ? void 0 : _c.find(style => { var _a; return ((_a = style.name) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'normal'; });
6
+ const fontId = (normal === null || normal === void 0 ? void 0 : normal.xfId) === undefined ? 0 : (_f = (_e = (_d = styles === null || styles === void 0 ? void 0 : styles.CellStyleXf) === null || _d === void 0 ? void 0 : _d[normal.xfId]) === null || _e === void 0 ? void 0 : _e.fontId) !== null && _f !== void 0 ? _f : 0;
7
+ const font = (_g = styles === null || styles === void 0 ? void 0 : styles.Fonts) === null || _g === void 0 ? void 0 : _g[fontId];
8
+ const size = Number(font === null || font === void 0 ? void 0 : font.sz);
9
+ if (/^(?:宋体|新宋体|simsun|nsimsun)$/i.test(((_h = font === null || font === void 0 ? void 0 : font.name) === null || _h === void 0 ? void 0 : _h.trim()) || '')
10
+ && Number.isFinite(size) && size >= 1 && size <= 409) {
11
+ return Math.max(1, Math.ceil(size * 96 / 72 / 2));
12
+ }
13
+ return 7;
14
+ };
15
+ export const readStoredSheetLayout = async (zip, part) => {
16
+ var _a, _b, _c, _d;
17
+ const file = zip.file(part);
18
+ if (!file)
19
+ return {};
20
+ const limit = 128 * 1024;
21
+ const header = await new Promise((resolve, reject) => {
22
+ let prefix = '';
23
+ let done = false;
24
+ const stream = file.internalStream('string');
25
+ const finish = () => {
26
+ if (done)
27
+ return;
28
+ done = true;
29
+ stream.pause();
30
+ resolve(prefix);
31
+ };
32
+ stream.on('data', chunk => {
33
+ if (done)
34
+ return;
35
+ prefix += chunk.slice(0, limit - prefix.length);
36
+ if (/<(?:[\w.-]+:)?(?:sheetFormatPr\b[^>]*>|sheetData\b)/.test(prefix) || prefix.length >= limit)
37
+ finish();
38
+ });
39
+ stream.on('end', finish);
40
+ stream.on('error', error => { if (!done) {
41
+ done = true;
42
+ reject(error);
43
+ } });
44
+ stream.resume();
45
+ });
46
+ const tag = (_a = /<(?:[\w.-]+:)?sheetFormatPr\b[^>]*>/.exec(header)) === null || _a === void 0 ? void 0 : _a[0];
47
+ if (!tag)
48
+ return {};
49
+ const root = ((_b = /<(?:[\w.-]+:)?worksheet\b[^>]*>/.exec(header)) === null || _b === void 0 ? void 0 : _b[0]) || '';
50
+ const namespaces = ((_c = root.match(/\sxmlns(?::[\w.-]+)?\s*=\s*(?:"[^"]*"|'[^']*')/g)) === null || _c === void 0 ? void 0 : _c.join('')) || '';
51
+ const element = (_d = new DOMParser().parseFromString(`<layout${namespaces}>${tag.replace(/\/?>(?:\s*)$/, '/>')}</layout>`, 'application/xml').documentElement) === null || _d === void 0 ? void 0 : _d.getElementsByTagName('*')[0];
52
+ const bounded = (name, max) => {
53
+ const raw = element === null || element === void 0 ? void 0 : element.getAttribute(name);
54
+ if (raw == null || raw.trim() === '')
55
+ return undefined;
56
+ const value = Number(raw);
57
+ return Number.isFinite(value) && value > 0 && value <= max ? value : undefined;
58
+ };
59
+ return { columnWidth: bounded('defaultColWidth', 255), rowHeightPt: bounded('defaultRowHeight', 409.5) };
60
+ };