@worksheet-js/excel 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,44 @@
1
+ # END USER LICENSE AGREEMENT (EULA)
2
+
3
+ **Product:** @worksheet-js/excel
4
+ **Copyright:** (c) 2024-present Worksheet Systems <support@worksheet.js>
5
+ **All Rights Reserved.**
6
+
7
+ IMPORTANT: PLEASE READ THIS LICENSE AGREEMENT CAREFULLY BEFORE USING THE SOFTWARE.
8
+
9
+ ### 1. PROPRIETARY RIGHTS
10
+
11
+ The @worksheet-js/excel spreadsheet import/export engine ("Software") is a proprietary product of Worksheet Systems and is protected by copyright laws and international treaty provisions. All intellectual property rights in and to the Software are and shall remain the exclusive property of Worksheet Systems.
12
+
13
+ ### 2. GRANT OF LICENSE
14
+
15
+ Subject to the terms and conditions of this Agreement and any applicable commercial terms, Worksheet Systems grants you a non-exclusive, non-transferable license to use the Software solely for your internal business purposes or as expressly permitted in a separate written agreement.
16
+
17
+ ### 3. RESTRICTIONS
18
+
19
+ You shall not, and shall not permit any third party to:
20
+
21
+ - Copy, modify, or create derivative works of the Software.
22
+ - Reverse engineer, decompile, or disassemble the Software, or otherwise attempt to derive the source code, except to the extent such restriction is expressly prohibited by applicable law.
23
+ - Sublicense, rent, lease, or lend the Software to any third party.
24
+ - Remove or alter any copyright, trademark, or other proprietary notices contained in the Software.
25
+
26
+ ### 4. CONFIDENTIALITY
27
+
28
+ The Software, including its structure, organization, and source code, constitutes valuable trade secrets and confidential information of Worksheet Systems. You agree to hold such information in strict confidence and not to disclose it to any third party.
29
+
30
+ ### 5. TERMINATION
31
+
32
+ This license is effective until terminated. Your rights under this License will terminate automatically without notice if you fail to comply with any term(s) of this Agreement. Upon termination, you shall cease all use of the Software and destroy all copies in your possession.
33
+
34
+ ### 6. NO WARRANTY
35
+
36
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE.
37
+
38
+ ### 7. LIMITATION OF LIABILITY
39
+
40
+ IN NO EVENT SHALL WORKSHEET SYSTEMS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE.
41
+
42
+ ### 8. GOVERNING LAW
43
+
44
+ This Agreement shall be governed by and construed in accordance with the laws of the jurisdiction in which Worksheet Systems is established, without regard to its conflict of law principles.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # @worksheet-js/excel
2
+
3
+ **High-performance spreadsheet I/O engine for XLSX, CSV, JSON, and HTML.**
4
+
5
+ `@worksheet-js/excel` is an industrial-grade engine dedicated to importing and exporting spreadsheet data. It handles complex OpenXML parsing for XLSX files and provides simple utilities for common text-based formats.
6
+
7
+ ## ✨ Key Features
8
+
9
+ - **XLSX Mastery**: Native support for large XLSX files using an optimized OpenXML reader.
10
+ - **Style Preservation**: Extracts and preserves fonts, fills, borders, and number formats.
11
+ - **Multi-Format Support**: Simplified I/O for CSV, TSV, JSON, and HTML tables.
12
+ - **Advanced Extraction**: Handles merged cells, conditional formatting rules, and hyperlinks.
13
+ - **Browser & Node.js**: Works seamlessly in both client-side and server-side environments.
14
+
15
+ ## ✨ Advanced Features
16
+
17
+ ### 🎨 High-Fidelity Style Extraction
18
+
19
+ Unlike basic parsers, `@worksheet-js/excel` extracts complex styling metadata, including:
20
+
21
+ - **Number Formats**: Currency, percentage, scientific, and custom accounting formats.
22
+ - **Borders**: Per-side border styles (solid, dashed, double) and colors.
23
+ - **Alignment**: Horizontal and vertical alignment, including text wrapping and indentations.
24
+
25
+ ### 🚀 Large File Optimization
26
+
27
+ The engine uses a streaming-like OpenXML parser to handle workbooks with 100,000+ rows while maintaining a low memory footprint.
28
+
29
+ ## 📦 Installation
30
+
31
+ ```bash
32
+ pnpm add @worksheet-js/excel
33
+ ```
34
+
35
+ ## 🚀 Usage
36
+
37
+ ### Loading a Workbook
38
+
39
+ ```typescript
40
+ import { WorkbookLoader } from '@worksheet-js/excel';
41
+
42
+ // Load from a browser File or ArrayBuffer
43
+ const { result, meta } = await WorkbookLoader.loadFromBuffer(xlsxArrayBuffer);
44
+
45
+ console.log(
46
+ 'Sheet Names:',
47
+ result.workbook.sheets.map((s) => s.name)
48
+ );
49
+ ```
50
+
51
+ ### Exporting a Workbook
52
+
53
+ ```typescript
54
+ import { WorkbookExporter } from '@worksheet-js/excel';
55
+
56
+ // Trigger a browser download of the current spreadsheet state
57
+ await WorkbookExporter.download(spreadsheetInstance, 'xlsx', 'report.xlsx');
58
+ ```
59
+
60
+ ## 🛠️ API Reference
61
+
62
+ ### `WorkbookLoader` (Static Methods)
63
+
64
+ - `loadFromBuffer(buffer: Uint8Array): Promise<{ result, meta }>`: The primary method for loading XLSX files.
65
+ - `loadFromCsvBuffer(buffer: Uint8Array | string, options?: CsvOptions)`: Parses CSV data.
66
+ - `loadFromJsonBuffer(buffer: Uint8Array | string, options?: JsonOptions)`: Parses structured JSON.
67
+ - `loadFromHtmlBuffer(buffer: Uint8Array | string, options?: HtmlOptions)`: Extracts data from `<table>` elements.
68
+
69
+ ### `WorkbookExporter` (Static Methods)
70
+
71
+ - `exportToBuffer(spreadsheet: Spreadsheet): Promise<Uint8Array>`: Generates an XLSX binary buffer.
72
+ - `exportToCsv(spreadsheet: Spreadsheet, sheetIndex?: number): string`: Generates a CSV string.
73
+ - `download(spreadsheet: Spreadsheet, format: 'xlsx' | 'csv', filename?: string)`: Triggers a browser-initiated file download.
74
+
75
+ ## 📄 License
76
+
77
+ Copyright (c) 2024-present Worksheet Systems. All rights reserved.
78
+ Proprietary software. Usage is subject to the [EULA](LICENSE) terms.
@@ -0,0 +1,423 @@
1
+ interface ParserResult {
2
+ workbook: WorkbookData;
3
+ warnings?: string[];
4
+ }
5
+ interface WorkbookData {
6
+ sheets: SheetData[];
7
+ activeSheetIndex: number;
8
+ }
9
+ /** Visual style properties for a cell */
10
+ interface CellStyle {
11
+ bold?: boolean;
12
+ italic?: boolean;
13
+ underline?: boolean;
14
+ strikethrough?: boolean;
15
+ fontFamily?: string;
16
+ fontSize?: number;
17
+ color?: string;
18
+ fillColor?: string;
19
+ align?: 'left' | 'center' | 'right';
20
+ valign?: 'top' | 'middle' | 'bottom';
21
+ wrap?: 'overflow' | 'wrap' | 'clip';
22
+ numberFormat?: string;
23
+ decimals?: number;
24
+ borderTop?: boolean;
25
+ borderBottom?: boolean;
26
+ borderLeft?: boolean;
27
+ borderRight?: boolean;
28
+ borderStyle?: string;
29
+ borderColor?: string;
30
+ borderWeight?: number;
31
+ borderTopColor?: string;
32
+ borderTopStyle?: string;
33
+ borderTopWeight?: number;
34
+ borderBottomColor?: string;
35
+ borderBottomStyle?: string;
36
+ borderBottomWeight?: number;
37
+ borderLeftColor?: string;
38
+ borderLeftStyle?: string;
39
+ borderLeftWeight?: number;
40
+ borderRightColor?: string;
41
+ borderRightStyle?: string;
42
+ borderRightWeight?: number;
43
+ currencyCode?: string;
44
+ direction?: 'ltr' | 'rtl';
45
+ }
46
+ interface SheetData {
47
+ id: string;
48
+ name: string;
49
+ state: 'visible' | 'hidden' | 'veryHidden';
50
+ cells: Record<string, CellData>;
51
+ merges: MergeData[];
52
+ columnWidths: Record<number, number>;
53
+ rowHeights: Record<number, number>;
54
+ hiddenColumns?: number[];
55
+ hiddenRows?: number[];
56
+ defaultColWidth?: number;
57
+ defaultRowHeight?: number;
58
+ images?: ImageData[];
59
+ hyperlinks?: HyperlinkData[];
60
+ dataValidations?: DataValidationData[];
61
+ conditionalFormatting?: ConditionalFormattingData[];
62
+ autoFilter?: AutoFilterData;
63
+ pivotTables?: any[];
64
+ }
65
+ interface AutoFilterData {
66
+ ref: string;
67
+ }
68
+ interface CsvOptions {
69
+ delimiter?: string;
70
+ quoteChar?: string;
71
+ worksheetName?: string;
72
+ }
73
+ interface JsonOptions {
74
+ worksheetName?: string;
75
+ }
76
+ interface HtmlOptions {
77
+ worksheetName?: string;
78
+ }
79
+ interface CellData {
80
+ value: any;
81
+ formula?: string;
82
+ style?: ParsedStyle;
83
+ type: CellType;
84
+ note?: string;
85
+ comments?: any[];
86
+ }
87
+ type CellType = 'string' | 'number' | 'boolean' | 'error' | 'date' | 'empty';
88
+ interface MergeData {
89
+ ref: string;
90
+ startRow: number;
91
+ startCol: number;
92
+ endRow: number;
93
+ endCol: number;
94
+ }
95
+ interface ImageData {
96
+ id: string;
97
+ name: string;
98
+ buffer: Uint8Array;
99
+ extension: string;
100
+ anchor: {
101
+ type: 'oneCell' | 'twoCell' | 'absolute';
102
+ from?: AnchorMarker;
103
+ to?: AnchorMarker;
104
+ ext?: {
105
+ cx: number;
106
+ cy: number;
107
+ };
108
+ pos?: {
109
+ x: number;
110
+ y: number;
111
+ };
112
+ };
113
+ }
114
+ interface AnchorMarker {
115
+ col: number;
116
+ colOff: number;
117
+ row: number;
118
+ rowOff: number;
119
+ }
120
+ interface HyperlinkData {
121
+ ref: string;
122
+ target?: string;
123
+ location?: string;
124
+ display?: string;
125
+ tooltip?: string;
126
+ }
127
+ interface DataValidationData {
128
+ sqref: string;
129
+ type: string;
130
+ allowBlank: boolean;
131
+ showInputMessage: boolean;
132
+ showErrorMessage: boolean;
133
+ promptTitle?: string;
134
+ prompt?: string;
135
+ errorTitle?: string;
136
+ error?: string;
137
+ formula1?: string;
138
+ formula2?: string;
139
+ }
140
+ interface ConditionalFormattingData {
141
+ sqref: string;
142
+ rules: CFRuleData[];
143
+ }
144
+ interface CFRuleData {
145
+ type: string;
146
+ priority: number;
147
+ operator?: string;
148
+ text?: string;
149
+ formula?: string[];
150
+ style?: ParsedStyle;
151
+ }
152
+ interface ParsedStyle {
153
+ font?: {
154
+ bold?: boolean;
155
+ italic?: boolean;
156
+ underline?: boolean;
157
+ strike?: boolean;
158
+ size?: number;
159
+ color?: string;
160
+ name?: string;
161
+ };
162
+ fill?: {
163
+ patternType?: string;
164
+ fgColor?: string;
165
+ bgColor?: string;
166
+ };
167
+ border?: {
168
+ left?: BorderStyle;
169
+ right?: BorderStyle;
170
+ top?: BorderStyle;
171
+ bottom?: BorderStyle;
172
+ diagonal?: BorderStyle & {
173
+ up?: boolean;
174
+ down?: boolean;
175
+ };
176
+ };
177
+ alignment?: {
178
+ horizontal?: 'left' | 'center' | 'right' | 'justify' | 'centerContinuous';
179
+ vertical?: 'top' | 'center' | 'bottom' | 'justify';
180
+ wrapText?: boolean;
181
+ };
182
+ numberFormat?: {
183
+ id: number;
184
+ formatCode: string;
185
+ };
186
+ }
187
+ interface BorderStyle {
188
+ style?: string;
189
+ color?: string;
190
+ }
191
+ interface Spreadsheet {
192
+ worksheets: any[];
193
+ current?: any;
194
+ }
195
+ interface SheetMeta {
196
+ worksheetName: string;
197
+ tabColor?: string;
198
+ hidden?: boolean;
199
+ minDimensions?: [number, number];
200
+ defaultColWidth?: number;
201
+ defaultRowHeight?: number;
202
+ minColWidth?: number;
203
+ minRowHeight?: number;
204
+ hiddenColumns?: number[];
205
+ hiddenRows?: number[];
206
+ frozenRows?: number;
207
+ frozenCols?: number;
208
+ direction?: 'ltr' | 'rtl';
209
+ }
210
+
211
+ /**
212
+ * @worksheet-js/excel - High-performance spreadsheet I/O engine
213
+ * (c) 2024-present Worksheet Systems <support@worksheet.js>
214
+ * All Rights Reserved.
215
+ *
216
+ * PROPRIETARY AND CONFIDENTIAL: Unauthorized copying of this file,
217
+ * via any medium is strictly prohibited.
218
+ */
219
+
220
+ /**
221
+ * WorkbookExporter — Orchestrates exporting Spreadsheet state to .xlsx and .csv files.
222
+ */
223
+ declare class WorkbookExporter {
224
+ /**
225
+ * Generates a binary XLSX buffer for the entire workbook.
226
+ *
227
+ * @param spreadsheet - The spreadsheet engine instance to export.
228
+ * @returns A promise resolving to the binary content of the .xlsx file.
229
+ */
230
+ static exportToBuffer(spreadsheet: Spreadsheet): Promise<Uint8Array>;
231
+ /**
232
+ * Generates a CSV string for a specific worksheet.
233
+ *
234
+ * @param spreadsheet - The spreadsheet engine instance.
235
+ * @param sheetIndex - The zero-based index of the sheet to export (default: 0).
236
+ */
237
+ static exportToCsv(spreadsheet: Spreadsheet, sheetIndex?: number): string;
238
+ /**
239
+ * Triggers a browser-initiated download of the spreadsheet data.
240
+ *
241
+ * @param spreadsheet - The spreadsheet engine instance.
242
+ * @param format - The target file format ('xlsx' or 'csv').
243
+ * @param filename - Optional custom filename.
244
+ */
245
+ static download(spreadsheet: Spreadsheet, format?: 'xlsx' | 'csv', filename?: string): Promise<void>;
246
+ private static _triggerDownload;
247
+ private static strToUint8;
248
+ private static getContentTypes;
249
+ private static getRootRels;
250
+ private static getWorkbookRels;
251
+ }
252
+
253
+ /**
254
+ * @worksheet-js/excel - High-performance spreadsheet I/O engine
255
+ * (c) 2024-present Worksheet Systems <support@worksheet.js>
256
+ * All Rights Reserved.
257
+ *
258
+ * PROPRIETARY AND CONFIDENTIAL: Unauthorized copying of this file,
259
+ * via any medium is strictly prohibited.
260
+ */
261
+
262
+ declare class WorkbookLoader {
263
+ /**
264
+ * Parses an XLSX file from a binary buffer.
265
+ *
266
+ * @param buffer - The binary data of the XLSX file (e.g., from a File object).
267
+ * @returns A promise resolving to the parsed workbook data and suggested sheet metadata.
268
+ */
269
+ static loadFromBuffer(buffer: Uint8Array): Promise<{
270
+ result: ParserResult;
271
+ meta: SheetMeta[];
272
+ }>;
273
+ /**
274
+ * Parses a CSV file from a buffer or string.
275
+ *
276
+ * @param buffer - The CSV data.
277
+ * @param options - CSV parsing configuration (delimiter, etc.).
278
+ */
279
+ static loadFromCsvBuffer(buffer: Uint8Array | string, options?: CsvOptions): {
280
+ result: ParserResult;
281
+ meta: SheetMeta[];
282
+ };
283
+ /**
284
+ * Parses a TSV (Tab-Separated Values) file.
285
+ */
286
+ static loadFromTsvBuffer(buffer: Uint8Array | string, options?: Omit<CsvOptions, 'delimiter'>): {
287
+ result: ParserResult;
288
+ meta: SheetMeta[];
289
+ };
290
+ /**
291
+ * Parses a JSON data structure representing a spreadsheet.
292
+ */
293
+ static loadFromJsonBuffer(buffer: Uint8Array | string, options?: JsonOptions): {
294
+ result: ParserResult;
295
+ meta: SheetMeta[];
296
+ };
297
+ /**
298
+ * Extracts data from HTML `<table>` elements.
299
+ */
300
+ static loadFromHtmlBuffer(buffer: Uint8Array | string, options?: HtmlOptions): {
301
+ result: ParserResult;
302
+ meta: SheetMeta[];
303
+ };
304
+ private static createMetaFromResult;
305
+ private static parseAddress;
306
+ }
307
+
308
+ /**
309
+ * Parses a raw XLSX buffer completely into a unified internal DOM representation.
310
+ *
311
+ * @param buffer - The contents of the .xlsx file
312
+ * @returns Parsed structured DOM for Worksheet Systems models
313
+ */
314
+ declare function parseXlsx(buffer: Uint8Array): Promise<ParserResult>;
315
+
316
+ interface IUnzipper {
317
+ getFile(path: string): Promise<Uint8Array | null>;
318
+ getFileAsString(path: string): Promise<string | null>;
319
+ getFilesPrefix(prefix: string): Promise<Record<string, Uint8Array>>;
320
+ close(): void;
321
+ }
322
+
323
+ declare class SyncUnzipper implements IUnzipper {
324
+ private files;
325
+ constructor(buffer: Uint8Array);
326
+ getFile(path: string): Promise<Uint8Array | null>;
327
+ getFileAsString(path: string): Promise<string | null>;
328
+ getFilesPrefix(prefix: string): Promise<Record<string, Uint8Array>>;
329
+ close(): void;
330
+ }
331
+
332
+ /**
333
+ * Converts an Excel serial date to a JavaScript Date object.
334
+ * Excel stores dates as the number of days since Jan 1, 1900.
335
+ * It also incorrectly considers 1900 a leap year, adding an extra day (Feb 29, 1900).
336
+ *
337
+ * @param serial - The Excel serial date number
338
+ * @returns The converted JavaScript Date object
339
+ */
340
+ declare function excelDateToJSDate(serial: number): Date;
341
+ /**
342
+ * Checks if a given number format code likely represents a date/time.
343
+ *
344
+ * @param formatCode The numberFormat code string
345
+ */
346
+ declare function isDateFormat(formatCode?: string): boolean;
347
+
348
+ /**
349
+ * Parses a CSV buffer or string into a standard ParserResult.
350
+ * Complies with RFC-4180 (handles newlines inside quoted fields).
351
+ */
352
+ declare function parseCsv(bufferOrString: Uint8Array | string, options?: CsvOptions): ParserResult;
353
+
354
+ /**
355
+ * Parses an HTML buffer or string (looking for <table> tags) into a standard ParserResult.
356
+
357
+ * Best effort extraction of text content and basic layout from tr/td tags.
358
+ */
359
+ declare function parseHtml(bufferOrString: Uint8Array | string, options?: HtmlOptions): ParserResult;
360
+
361
+ /**
362
+ * Parses a JSON buffer or string into a standard ParserResult.
363
+
364
+ * Supports:
365
+ * - Array of Arrays: `[["Header1", "Header2"], [1, 2]]`
366
+ * - Array of Objects: `[{"Name": "Alice", "Age": 30}, {"Name": "Bob", "Age": 25}]`
367
+ */
368
+ declare function parseJson(bufferOrString: Uint8Array | string, options?: JsonOptions): ParserResult;
369
+
370
+ declare class ParserError extends Error {
371
+ readonly context?: Record<string, any> | undefined;
372
+ constructor(message: string, context?: Record<string, any> | undefined);
373
+ }
374
+
375
+ /**
376
+ * Parses a TSV or TXT buffer/string into a standard ParserResult.
377
+ * This is a thin wrapper over the Csv parser, defaulting the delimiter to a tab (\t).
378
+ */
379
+ declare function parseTsv(bufferOrString: Uint8Array | string, options?: Omit<CsvOptions, 'delimiter'>): ParserResult;
380
+
381
+ /**
382
+ * XmlWriter — Helper to generate OpenXML compliant XML strings.
383
+ * Minimal implementation for XLSX exporting.
384
+ */
385
+ declare class XmlWriter {
386
+ static escape(str: string): string;
387
+ static workbook(sheetNames: string[], activeSheetIndex?: number, sheetStates?: string[]): string;
388
+ static worksheet(rows: Array<Array<{
389
+ v: any;
390
+ f?: string;
391
+ } | null | undefined>>, options?: {
392
+ merges?: Array<{
393
+ x1: number;
394
+ y1: number;
395
+ x2: number;
396
+ y2: number;
397
+ }>;
398
+ cols?: Map<number, number>;
399
+ rowHeights?: Map<number, number>;
400
+ hiddenCols?: Set<number>;
401
+ hiddenRows?: Set<number>;
402
+ frozenRows?: number;
403
+ frozenCols?: number;
404
+ tabColor?: string;
405
+ defaultColWidth?: number;
406
+ defaultRowHeight?: number;
407
+ defaultWidth?: number;
408
+ defaultHeight?: number;
409
+ styles?: Map<string, number>;
410
+ autoFilter?: string;
411
+ dataValidations?: any[];
412
+ hyperlinks?: any[];
413
+ conditionalFormatting?: any[];
414
+ drawingId?: string;
415
+ rightToLeft?: boolean;
416
+ }): string;
417
+ static coordsToAddr(x: number, y: number): string;
418
+ static coreProps(title?: string): string;
419
+ static appProps(): string;
420
+ static drawings(images: any[]): string;
421
+ }
422
+
423
+ export { type AnchorMarker, type AutoFilterData, type BorderStyle, type CFRuleData, type CellData, type CellStyle, type CellType, type ConditionalFormattingData, type CsvOptions, type DataValidationData, type HtmlOptions, type HyperlinkData, type ImageData, type JsonOptions, type MergeData, type ParsedStyle, ParserError, type ParserResult, type SheetData, type SheetMeta, type Spreadsheet, SyncUnzipper, type WorkbookData, WorkbookExporter, WorkbookLoader, XmlWriter, excelDateToJSDate, isDateFormat, parseCsv, parseHtml, parseJson, parseTsv, parseXlsx };