CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-xlsx

SheetJS Spreadsheet data parser and writer for multiple formats including Excel, CSV, and OpenDocument

Overview
Eval results
Files

core-io.mddocs/

Core I/O Operations

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.

Capabilities

Read Function

Parses spreadsheet data from various input sources including files, binary data, and Base64 strings.

/**
 * Parse spreadsheet data from various sources
 * @param data - Input data (ArrayBuffer, Buffer, base64 string, etc.)
 * @param opts - Parsing options to control behavior
 * @returns WorkBook object containing parsed spreadsheet data
 */
function read(data: any, opts?: ParsingOptions): WorkBook;

interface ParsingOptions extends CommonOptions {
  /** Input data type hint */
  type?: "base64" | "binary" | "buffer" | "array" | "file" | "string";
  /** Default codepage */
  codepage?: number;
  /** Save formulae to the .f field */
  cellFormula?: boolean;
  /** Parse rich text and save HTML to the .h field */
  cellHTML?: boolean;
  /** Save number format string to the .z field */
  cellNF?: boolean;
  /** Generate formatted text to the .w field */
  cellText?: boolean;
  /** Override default date format (code 14) */
  dateNF?: string;
  /** Field Separator ("Delimiter" override) */
  FS?: string;
  /** If >0, read the first sheetRows rows */
  sheetRows?: number;
  /** If true, parse calculation chains */
  bookDeps?: boolean;
  /** If true, add raw files to book object */
  bookFiles?: boolean;
  /** If true, only parse enough to get book metadata */
  bookProps?: boolean;
  /** If true, only parse enough to get the sheet names */
  bookSheets?: boolean;
  /** If specified, only parse the specified sheets or sheet names */
  sheets?: number | string | Array<number | string>;
  /** If true, plaintext parsing will not parse values */
  raw?: boolean;
  /** If true, preserve _xlfn. prefixes in formula function names */
  xlfn?: boolean;
  /** Dense mode */
  dense?: boolean;
  /** PRN parsing mode */
  PRN?: boolean;
}

Usage Examples:

import { read } from "xlsx";

// Read from file buffer (Node.js)
import * as fs from "fs";
const fileBuffer = fs.readFileSync("spreadsheet.xlsx");
const workbook = read(fileBuffer);

// Read from base64 string
const base64Data = "UEsDBBQAAAAA..."; // base64 encoded xlsx
const workbook2 = read(base64Data, { type: "base64" });

// Read with specific options
const workbook3 = read(fileBuffer, {
  sheetRows: 1000,    // Only read first 1000 rows
  cellDates: true,    // Parse dates as Date objects
  bookVBA: true       // Include VBA macros
});

// Access parsed data
console.log(workbook.SheetNames);           // Array of sheet names
console.log(workbook.Sheets["Sheet1"]);     // First worksheet data

Read File Function (Node.js Only)

Reads and parses a spreadsheet file directly from the filesystem.

/**
 * Read and parse a spreadsheet file from filesystem (Node.js only)
 * @param filename - Path to the spreadsheet file
 * @param opts - Parsing options
 * @returns WorkBook object containing parsed file data
 */
function readFile(filename: string, opts?: ParsingOptions): WorkBook;

Usage Examples:

import { readFile } from "xlsx";

// Simple file read
const workbook = readFile("data.xlsx");

// Read with options
const workbook2 = readFile("large-file.xlsx", {
  sheetRows: 500,     // Limit rows to avoid memory issues
  cellText: false,    // Skip generating cell text
  cellHTML: false     // Skip generating cell HTML
});

// Handle different formats
const csvBook = readFile("data.csv");
const odsBook = readFile("data.ods");
const xlsBook = readFile("legacy.xls");

Write Function

Converts a WorkBook object to various output formats in memory.

/**
 * Convert WorkBook to output format in memory
 * @param data - WorkBook object to write
 * @param opts - Writing options controlling output format and behavior
 * @returns Output data in specified format (Buffer, string, etc.)
 */
function write(data: WorkBook, opts: WritingOptions): any;

interface WritingOptions extends CommonOptions {
  /** Output data encoding */
  type?: "base64" | "binary" | "buffer" | "file" | "array" | "string";
  /** Generate Shared String Table */
  bookSST?: boolean;
  /** File format of generated workbook */
  bookType?: BookType;
  /** Use ZIP compression for ZIP-based formats */
  compression?: boolean;
  /** Suppress "number stored as text" errors in generated files */
  ignoreEC?: boolean;
  /** Override workbook properties on save */
  Props?: Properties;
  /** Base64 encoding of NUMBERS base for exports */
  numbers?: string;
  /** Name of Worksheet (for single-sheet formats) */
  sheet?: string;
}

Usage Examples:

import { write, utils } from "xlsx";

// Create a workbook
const workbook = utils.book_new();
const worksheet = utils.json_to_sheet([
  { Name: "Alice", Age: 25 },
  { Name: "Bob", Age: 30 }
]);
utils.book_append_sheet(workbook, worksheet, "People");

// Write as XLSX buffer
const xlsxBuffer = write(workbook, { 
  bookType: "xlsx", 
  type: "buffer" 
});

// Write as CSV string  
const csvString = write(workbook, { 
  bookType: "csv", 
  type: "string" 
});

// Write as base64 for web transfer
const base64Data = write(workbook, { 
  bookType: "xlsx", 
  type: "base64" 
});

// Write with custom CSV separators
const customCsv = write(workbook, {
  bookType: "csv",
  type: "string",
  FS: ";",    // Semicolon field separator
  RS: "\r\n"  // Windows line endings
});

Write File Function (Node.js Only)

Writes a WorkBook object directly to a file on the filesystem.

/**
 * Write WorkBook object to file on filesystem (Node.js only)
 * @param data - WorkBook object to write
 * @param filename - Output file path (extension determines format)
 * @param opts - Writing options
 */
function writeFile(data: WorkBook, filename: string, opts?: WritingOptions): void;

Usage Examples:

import { writeFile, utils } from "xlsx";

const workbook = utils.book_new();
const worksheet = utils.json_to_sheet([
  { Product: "Laptop", Price: 999, Stock: 5 },
  { Product: "Mouse", Price: 25, Stock: 100 }
]);
utils.book_append_sheet(workbook, worksheet, "Inventory");

// Write to different formats (format determined by extension)
writeFile(workbook, "output.xlsx");      // Excel format
writeFile(workbook, "output.csv");       // CSV format  
writeFile(workbook, "output.ods");       // OpenDocument format
writeFile(workbook, "output.html");      // HTML table format

// Write with options
writeFile(workbook, "compressed.xlsx", {
  compression: true,    // Enable compression
  Props: true          // Include document properties
});

Write File Async Function (Node.js Only)

Asynchronously writes a WorkBook object to a file with callback support.

/**
 * Asynchronously write WorkBook to file with callback support (Node.js only)
 * @param filename - Output file path
 * @param data - WorkBook object to write
 * @param opts - Writing options or callback function
 * @param cb - Optional callback function
 */
function writeFileAsync(
  filename: string, 
  data: WorkBook, 
  opts: WritingOptions | (() => void), 
  cb?: () => void
): any;

Usage Examples:

import { writeFileAsync, utils } from "xlsx";

const workbook = utils.book_new();
const worksheet = utils.json_to_sheet([{ A: 1, B: 2 }]);
utils.book_append_sheet(workbook, worksheet, "Sheet1");

// With callback only
writeFileAsync("async-output.xlsx", workbook, () => {
  console.log("File written successfully!");
});

// With options and callback
writeFileAsync("async-compressed.xlsx", workbook, 
  { compression: true }, 
  () => {
    console.log("Compressed file written!");
  }
);

XLSX-Specific Write Functions

Specialized functions that force XLSX format output regardless of filename extension.

/**
 * Write WorkBook as XLSX format to memory
 * @param data - WorkBook object to write
 * @param opts - Writing options (bookType forced to "xlsx")
 * @returns XLSX data in specified output type
 */
function writeXLSX(data: WorkBook, opts: WritingOptions): any;

/**
 * Write WorkBook as XLSX format to file (Node.js only)
 * @param data - WorkBook object to write  
 * @param filename - Output file path
 * @param opts - Writing options (bookType forced to "xlsx")
 */
function writeFileXLSX(data: WorkBook, filename: string, opts?: WritingOptions): void;

Usage Examples:

import { writeXLSX, writeFileXLSX, utils } from "xlsx";

const workbook = utils.book_new();
const worksheet = utils.json_to_sheet([{ Data: "Example" }]);
utils.book_append_sheet(workbook, worksheet, "Sheet1");

// Force XLSX format in memory
const xlsxBuffer = writeXLSX(workbook, { type: "buffer" });

// Force XLSX format to file (Node.js)
writeFileXLSX(workbook, "forced-xlsx.bin");  // Creates XLSX despite .bin extension

Configuration Functions (ES Modules Only)

Special configuration functions available only when using ES modules for customizing internal dependencies.

/**
 * Set internal filesystem instance for ES module usage
 * @param fs - Filesystem implementation (typically Node.js fs module)
 */
function set_fs(fs: any): void;

/**
 * Set internal codepage tables for character encoding
 * @param cptable - Codepage table implementation
 */
function set_cptable(cptable: any): void;

Usage Examples:

// ES modules only - configure internal dependencies
import { set_fs, set_cptable } from "xlsx";
import * as fs from "fs";
import * as cptable from "codepage";

// Configure filesystem (required for file operations in ES modules)
set_fs(fs);

// Configure codepage tables (required for legacy format support)
set_cptable(cptable);

// Now file operations will work properly
import { readFile } from "xlsx";
const workbook = readFile("data.xlsx");

Error Handling

All I/O functions may throw exceptions for various error conditions:

import { readFile } from "xlsx";

try {
  const workbook = readFile("nonexistent.xlsx");
} catch (error) {
  if (error.code === 'ENOENT') {
    console.error("File not found");
  } else if (error.message.includes("Unsupported file")) {
    console.error("Unsupported file format");
  } else {
    console.error("Error reading file:", error.message);
  }
}

Format Detection

XLSX automatically detects input formats, but you can provide hints for better performance:

import { read } from "xlsx";

// Let XLSX auto-detect
const workbook1 = read(fileData);

// Provide format hint for better performance
const workbook2 = read(fileData, { type: "buffer" });

// Force specific parsing for ambiguous data
const workbook3 = read(csvString, { type: "string" });

Install with Tessl CLI

npx tessl i tessl/npm-xlsx

docs

cell-operations.md

core-io.md

data-conversion.md

index.md

streaming.md

workbook-management.md

tile.json