0
# Core I/O Operations
1
2
Primary functions for reading and writing spreadsheet data across multiple formats. These functions provide the foundation for all file operations and data processing in XLSX.
3
4
## Capabilities
5
6
### Read Function
7
8
Parses spreadsheet data from various input sources including files, binary data, and Base64 strings.
9
10
```typescript { .api }
11
/**
12
* Parse spreadsheet data from various sources
13
* @param data - Input data (ArrayBuffer, Buffer, base64 string, etc.)
14
* @param opts - Parsing options to control behavior
15
* @returns WorkBook object containing parsed spreadsheet data
16
*/
17
function read(data: any, opts?: ParsingOptions): WorkBook;
18
19
interface ParsingOptions extends CommonOptions {
20
/** Input data type hint */
21
type?: "base64" | "binary" | "buffer" | "array" | "file" | "string";
22
/** Default codepage */
23
codepage?: number;
24
/** Save formulae to the .f field */
25
cellFormula?: boolean;
26
/** Parse rich text and save HTML to the .h field */
27
cellHTML?: boolean;
28
/** Save number format string to the .z field */
29
cellNF?: boolean;
30
/** Generate formatted text to the .w field */
31
cellText?: boolean;
32
/** Override default date format (code 14) */
33
dateNF?: string;
34
/** Field Separator ("Delimiter" override) */
35
FS?: string;
36
/** If >0, read the first sheetRows rows */
37
sheetRows?: number;
38
/** If true, parse calculation chains */
39
bookDeps?: boolean;
40
/** If true, add raw files to book object */
41
bookFiles?: boolean;
42
/** If true, only parse enough to get book metadata */
43
bookProps?: boolean;
44
/** If true, only parse enough to get the sheet names */
45
bookSheets?: boolean;
46
/** If specified, only parse the specified sheets or sheet names */
47
sheets?: number | string | Array<number | string>;
48
/** If true, plaintext parsing will not parse values */
49
raw?: boolean;
50
/** If true, preserve _xlfn. prefixes in formula function names */
51
xlfn?: boolean;
52
/** Dense mode */
53
dense?: boolean;
54
/** PRN parsing mode */
55
PRN?: boolean;
56
}
57
```
58
59
**Usage Examples:**
60
61
```typescript
62
import { read } from "xlsx";
63
64
// Read from file buffer (Node.js)
65
import * as fs from "fs";
66
const fileBuffer = fs.readFileSync("spreadsheet.xlsx");
67
const workbook = read(fileBuffer);
68
69
// Read from base64 string
70
const base64Data = "UEsDBBQAAAAA..."; // base64 encoded xlsx
71
const workbook2 = read(base64Data, { type: "base64" });
72
73
// Read with specific options
74
const workbook3 = read(fileBuffer, {
75
sheetRows: 1000, // Only read first 1000 rows
76
cellDates: true, // Parse dates as Date objects
77
bookVBA: true // Include VBA macros
78
});
79
80
// Access parsed data
81
console.log(workbook.SheetNames); // Array of sheet names
82
console.log(workbook.Sheets["Sheet1"]); // First worksheet data
83
```
84
85
### Read File Function (Node.js Only)
86
87
Reads and parses a spreadsheet file directly from the filesystem.
88
89
```typescript { .api }
90
/**
91
* Read and parse a spreadsheet file from filesystem (Node.js only)
92
* @param filename - Path to the spreadsheet file
93
* @param opts - Parsing options
94
* @returns WorkBook object containing parsed file data
95
*/
96
function readFile(filename: string, opts?: ParsingOptions): WorkBook;
97
```
98
99
**Usage Examples:**
100
101
```typescript
102
import { readFile } from "xlsx";
103
104
// Simple file read
105
const workbook = readFile("data.xlsx");
106
107
// Read with options
108
const workbook2 = readFile("large-file.xlsx", {
109
sheetRows: 500, // Limit rows to avoid memory issues
110
cellText: false, // Skip generating cell text
111
cellHTML: false // Skip generating cell HTML
112
});
113
114
// Handle different formats
115
const csvBook = readFile("data.csv");
116
const odsBook = readFile("data.ods");
117
const xlsBook = readFile("legacy.xls");
118
```
119
120
### Write Function
121
122
Converts a WorkBook object to various output formats in memory.
123
124
```typescript { .api }
125
/**
126
* Convert WorkBook to output format in memory
127
* @param data - WorkBook object to write
128
* @param opts - Writing options controlling output format and behavior
129
* @returns Output data in specified format (Buffer, string, etc.)
130
*/
131
function write(data: WorkBook, opts: WritingOptions): any;
132
133
interface WritingOptions extends CommonOptions {
134
/** Output data encoding */
135
type?: "base64" | "binary" | "buffer" | "file" | "array" | "string";
136
/** Generate Shared String Table */
137
bookSST?: boolean;
138
/** File format of generated workbook */
139
bookType?: BookType;
140
/** Use ZIP compression for ZIP-based formats */
141
compression?: boolean;
142
/** Suppress "number stored as text" errors in generated files */
143
ignoreEC?: boolean;
144
/** Override workbook properties on save */
145
Props?: Properties;
146
/** Base64 encoding of NUMBERS base for exports */
147
numbers?: string;
148
/** Name of Worksheet (for single-sheet formats) */
149
sheet?: string;
150
}
151
```
152
153
**Usage Examples:**
154
155
```typescript
156
import { write, utils } from "xlsx";
157
158
// Create a workbook
159
const workbook = utils.book_new();
160
const worksheet = utils.json_to_sheet([
161
{ Name: "Alice", Age: 25 },
162
{ Name: "Bob", Age: 30 }
163
]);
164
utils.book_append_sheet(workbook, worksheet, "People");
165
166
// Write as XLSX buffer
167
const xlsxBuffer = write(workbook, {
168
bookType: "xlsx",
169
type: "buffer"
170
});
171
172
// Write as CSV string
173
const csvString = write(workbook, {
174
bookType: "csv",
175
type: "string"
176
});
177
178
// Write as base64 for web transfer
179
const base64Data = write(workbook, {
180
bookType: "xlsx",
181
type: "base64"
182
});
183
184
// Write with custom CSV separators
185
const customCsv = write(workbook, {
186
bookType: "csv",
187
type: "string",
188
FS: ";", // Semicolon field separator
189
RS: "\r\n" // Windows line endings
190
});
191
```
192
193
### Write File Function (Node.js Only)
194
195
Writes a WorkBook object directly to a file on the filesystem.
196
197
```typescript { .api }
198
/**
199
* Write WorkBook object to file on filesystem (Node.js only)
200
* @param data - WorkBook object to write
201
* @param filename - Output file path (extension determines format)
202
* @param opts - Writing options
203
*/
204
function writeFile(data: WorkBook, filename: string, opts?: WritingOptions): void;
205
```
206
207
**Usage Examples:**
208
209
```typescript
210
import { writeFile, utils } from "xlsx";
211
212
const workbook = utils.book_new();
213
const worksheet = utils.json_to_sheet([
214
{ Product: "Laptop", Price: 999, Stock: 5 },
215
{ Product: "Mouse", Price: 25, Stock: 100 }
216
]);
217
utils.book_append_sheet(workbook, worksheet, "Inventory");
218
219
// Write to different formats (format determined by extension)
220
writeFile(workbook, "output.xlsx"); // Excel format
221
writeFile(workbook, "output.csv"); // CSV format
222
writeFile(workbook, "output.ods"); // OpenDocument format
223
writeFile(workbook, "output.html"); // HTML table format
224
225
// Write with options
226
writeFile(workbook, "compressed.xlsx", {
227
compression: true, // Enable compression
228
Props: true // Include document properties
229
});
230
```
231
232
### Write File Async Function (Node.js Only)
233
234
Asynchronously writes a WorkBook object to a file with callback support.
235
236
```typescript { .api }
237
/**
238
* Asynchronously write WorkBook to file with callback support (Node.js only)
239
* @param filename - Output file path
240
* @param data - WorkBook object to write
241
* @param opts - Writing options or callback function
242
* @param cb - Optional callback function
243
*/
244
function writeFileAsync(
245
filename: string,
246
data: WorkBook,
247
opts: WritingOptions | (() => void),
248
cb?: () => void
249
): any;
250
```
251
252
**Usage Examples:**
253
254
```typescript
255
import { writeFileAsync, utils } from "xlsx";
256
257
const workbook = utils.book_new();
258
const worksheet = utils.json_to_sheet([{ A: 1, B: 2 }]);
259
utils.book_append_sheet(workbook, worksheet, "Sheet1");
260
261
// With callback only
262
writeFileAsync("async-output.xlsx", workbook, () => {
263
console.log("File written successfully!");
264
});
265
266
// With options and callback
267
writeFileAsync("async-compressed.xlsx", workbook,
268
{ compression: true },
269
() => {
270
console.log("Compressed file written!");
271
}
272
);
273
```
274
275
### XLSX-Specific Write Functions
276
277
Specialized functions that force XLSX format output regardless of filename extension.
278
279
```typescript { .api }
280
/**
281
* Write WorkBook as XLSX format to memory
282
* @param data - WorkBook object to write
283
* @param opts - Writing options (bookType forced to "xlsx")
284
* @returns XLSX data in specified output type
285
*/
286
function writeXLSX(data: WorkBook, opts: WritingOptions): any;
287
288
/**
289
* Write WorkBook as XLSX format to file (Node.js only)
290
* @param data - WorkBook object to write
291
* @param filename - Output file path
292
* @param opts - Writing options (bookType forced to "xlsx")
293
*/
294
function writeFileXLSX(data: WorkBook, filename: string, opts?: WritingOptions): void;
295
```
296
297
**Usage Examples:**
298
299
```typescript
300
import { writeXLSX, writeFileXLSX, utils } from "xlsx";
301
302
const workbook = utils.book_new();
303
const worksheet = utils.json_to_sheet([{ Data: "Example" }]);
304
utils.book_append_sheet(workbook, worksheet, "Sheet1");
305
306
// Force XLSX format in memory
307
const xlsxBuffer = writeXLSX(workbook, { type: "buffer" });
308
309
// Force XLSX format to file (Node.js)
310
writeFileXLSX(workbook, "forced-xlsx.bin"); // Creates XLSX despite .bin extension
311
```
312
313
## Configuration Functions (ES Modules Only)
314
315
Special configuration functions available only when using ES modules for customizing internal dependencies.
316
317
```typescript { .api }
318
/**
319
* Set internal filesystem instance for ES module usage
320
* @param fs - Filesystem implementation (typically Node.js fs module)
321
*/
322
function set_fs(fs: any): void;
323
324
/**
325
* Set internal codepage tables for character encoding
326
* @param cptable - Codepage table implementation
327
*/
328
function set_cptable(cptable: any): void;
329
```
330
331
**Usage Examples:**
332
333
```typescript
334
// ES modules only - configure internal dependencies
335
import { set_fs, set_cptable } from "xlsx";
336
import * as fs from "fs";
337
import * as cptable from "codepage";
338
339
// Configure filesystem (required for file operations in ES modules)
340
set_fs(fs);
341
342
// Configure codepage tables (required for legacy format support)
343
set_cptable(cptable);
344
345
// Now file operations will work properly
346
import { readFile } from "xlsx";
347
const workbook = readFile("data.xlsx");
348
```
349
350
## Error Handling
351
352
All I/O functions may throw exceptions for various error conditions:
353
354
```typescript
355
import { readFile } from "xlsx";
356
357
try {
358
const workbook = readFile("nonexistent.xlsx");
359
} catch (error) {
360
if (error.code === 'ENOENT') {
361
console.error("File not found");
362
} else if (error.message.includes("Unsupported file")) {
363
console.error("Unsupported file format");
364
} else {
365
console.error("Error reading file:", error.message);
366
}
367
}
368
```
369
370
## Format Detection
371
372
XLSX automatically detects input formats, but you can provide hints for better performance:
373
374
```typescript
375
import { read } from "xlsx";
376
377
// Let XLSX auto-detect
378
const workbook1 = read(fileData);
379
380
// Provide format hint for better performance
381
const workbook2 = read(fileData, { type: "buffer" });
382
383
// Force specific parsing for ambiguous data
384
const workbook3 = read(csvString, { type: "string" });
385
```