SheetXL - v0.8.0-beta.9+sites.210.e2d420901
    Preparing search index...

    Interface IWorkbookIO

    Interface for workbook input/output operations across multiple source types and formats.

    This interface provides a flexible I/O system with two independent dimensions:

    The physical location or container of the workbook data:

    • File: Local file system files (File objects)
    • Blob: Binary data blobs (from canvas, clipboard, etc.)
    • URL/Fetch: Remote resources fetched via HTTP/HTTPS
    • ArrayBuffer: Raw binary data in memory
    • Base64: Base64-encoded strings
    • Stream: Streaming data (ReadableStream)

    The encoding/file format of the workbook data:

    • sxl: SheetXL format
    • xlsx: Excel 2007+ format (Office Open XML)
    • csv: Comma-separated values
    • xml: Excel 2003 XML format
    • And other registered formats

    Any source type can contain any format type. For example:

    • A File could contain sxl, xlsx, csv data
    • A URL could point to an sxl, xlsx, or csv file
    • An ArrayBuffer could hold sxl, xlsx, or csv data

    The system automatically detects the format type from:

    • File extensions (.xlsx, .csv, etc.)
    • MIME types (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)
    • Content sniffing (examining the actual data)
    // Example 1: File source with xlsx format
    const wb = await WorkbookIO.read({ source: fileObject }); // Auto-detects .xlsx

    // Example 2: URL source with csv format
    const wb = await WorkbookIO.read({ source: 'https://example.com/data.csv' });

    // Example 3: ArrayBuffer source with explicit format
    const wb = await WorkbookIO.read({
    source: arrayBuffer,
    format: 'xlsx' // Format can't be auto-detected or forced
    });
    interface IWorkbookIO {
        isIWorkbookIO: true;
        addCommitListener(listener: ITransaction.ICommitSource.IListeners): Remove;
        addListeners(listeners: Listeners, options?: IListener.Options): Remove;
        canRead(): boolean;
        canWrite(): boolean;
        getBackingStore(): IBackingStore;
        getOrigin(pathOrUrl: string): IWorkbookIO.Origin;
        getReadFormats(options?: GetFormatsOptions): Promise<FormatType[]>;
        getWriteFormats(options?: GetFormatsOptions): Promise<FormatType[]>;
        install(plugin: Plugin): Promise<void>;
        read<T extends ReadOptions = ReadOptions>(
            sourceOrOptions?: string | IWorkbookIO.Origin | T,
        ): Promise<IWorkbook | null>;
        setBackingStore(store: IBackingStore | null): void;
        write<T extends WriteOptions = WriteOptions>(
            workbook: IWorkbook,
            target?: string | IWorkbookIO.Origin | T,
            options?: T,
        ): Promise<IWorkbookIO.Origin | null>;
        writeArrayBuffer<T extends WriteOptions = WriteOptions>(
            workbook: IWorkbook,
            options?: T,
        ): Promise<ArrayBufferLike>;
        writeAs<T extends WriteAsOptions = WriteAsOptions>(
            workbook: IWorkbook,
            target: string | IWorkbookIO.Origin,
            options?: T,
        ): Promise<IWorkbookIO.Origin | null>;
    }

    Hierarchy (View Summary)

    Index
    isIWorkbookIO: true

    For runtime type checking.

    • Whether the active IWorkbookIO.IBackingStore provides its own read (interactive source acquisition).

      Returns boolean

      Reflects the active store's own capability — not the platform read fallback. A write-only override reports false even though IWorkbookIO.read of in-hand bytes still works via the fallback. Use to gate open / drag-drop affordances (and to release their shortcuts).

    • Whether the active IWorkbookIO.IBackingStore can persist workbooks (implements write).

      Returns boolean

      Reflects the active store's own capability — a UI-capability probe (e.g. enable Save), not a guarantee about a particular IWorkbookIO.write call. Use to gate save affordances.

    • Returns available read format types (encoding formats that can be read).

      Parameters

      • Optionaloptions: GetFormatsOptions

        Optional filters to narrow down the format types

      Returns Promise<FormatType[]>

      Array of format type definitions that can decode workbook data

      Returns format types (encoding formats like sxl, xlsx, csv), not source types. Each format type includes:

      • File extensions it supports (e.g., ['.xlsx', '.xlsm'])
      • MIME type (e.g., 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
      • Handler function for decoding that format

      These format types work with any source type (File, URL, ArrayBuffer, etc.).

      // Get all available read formats
      const allFormats = workbookIO.getReadFormats();
      console.log(allFormats.map(f => f.key)); // ['sxl', 'xlsx', 'csv', ...]

      // Find format by file extension
      const csvFormat = workbookIO.getReadFormats({ ext: '.csv' });

      // Find format by MIME type
      const xlsxFormat = workbookIO.getReadFormats({
      mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });
    • Returns available write format types (encoding formats that can be written).

      Parameters

      • Optionaloptions: GetFormatsOptions

        Optional filters to narrow down the format types.

      Returns Promise<FormatType[]>

      Array of format type definitions that can encode workbook data

      Returns format types (encoding formats like sxl, xlsx, csv), not source types. Each format type includes:

      • File extension it produces (e.g., '.xlsx')
      • MIME type (e.g., 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
      • Handler function for encoding that format

      The encoded data can then be written to any source type (File, ArrayBuffer, etc.).

      // Get all available write formats
      const allFormats = workbookIO.getWriteFormats();
      console.log(allFormats.map(f => f.key)); // ['sxl', 'xlsx', 'csv', ...]

      // Find format by extension
      const xlsxFormat = workbookIO.getWriteFormats({ ext: '.xlsx' });

      // Build a file type picker for UI
      const formats = workbookIO.getWriteFormats();
      const fileTypes = formats.map(f => ({
      description: f.description,
      accept: { [f.mimeType]: [f.ext] }
      }));
    • Adds a new read format type to the I/O system.

      Parameters

      Returns Promise<void>

    • Reads a workbook from any source type with automatic format detection.

      Type Parameters

      Parameters

      • OptionalsourceOrOptions: string | IWorkbookIO.Origin | T

        Configuration specifying the source and optional format. Can also be passed directly as a string (URL, path, or data URI) as a shorthand for { source: string }. Omit the source entirely to let the active IWorkbookIO.IBackingStore resolve one (e.g. an open picker in the browser).

      Returns Promise<IWorkbook | null>

      A promise resolving to the decoded IWorkbook, or null if no source was resolved (e.g. the user cancelled an open picker). All read metadata — path, display name, resource type (format), size — lives on the workbook's origin handle; there is no separate details object.

      When the source type cannot be detected or accessed

      When no appropriate format handler is available for the detected format

      When the read operation fails (corrupt file, network error, etc.)

      The method automatically determines the source type (where data comes from):

      Input Pattern Detected Source Type Example
      { base64: "..." } Base64 string { base64: "iVBORw0K..." }
      { input: "..." } Fetch/URL { input: "https://api.example.com" }
      String starting with data: Base64 data URI "data:application/json;base64,..."
      String starting with http:// or https:// Remote URL "https://example.com/file.xlsx"
      String starting with /, ./, ../ Relative/absolute path "./data/workbook.csv"
      Other strings Treated as URL/path "workbook.xlsx"
      File object Browser File API <input type="file"> result
      Blob object Binary data blob Canvas, clipboard, etc.
      ArrayBuffer or TypedArray Binary buffer Raw bytes in memory
      ReadableStream Streaming data Converted to buffer first
      Promise<T> Async source Resolved, then re-detected
      () => T Lazy source Invoked, then re-detected

      The method automatically determines the format type (how data is encoded):

      1. File extension from source name (.sxl, .xlsx, .csv)
      2. MIME type from HTTP response headers
      3. Content inspection by examining magic bytes/signatures
      4. Explicit format via options.format
      // Auto-detect everything from a File object
      const wb = await WorkbookIO.read({ source: fileInput.files[0] });
      console.log(wb!.getName(), wb!.getOrigin().getPath());

      // Fetch from URL (auto-detects format from extension or Content-Type)
      const wb = await WorkbookIO.read({
      source: 'https://example.com/spreadsheet.xlsx'
      });

      // ArrayBuffer with explicit format (can't be auto-detected)
      const wb = await WorkbookIO.read({
      source: sxlArrayBuffer,
      format: 'sxl'
      });

      // Lazy loading with progress callback
      const wb = await WorkbookIO.read({
      source: async () => await fetch('/api/workbook').then(r => r.arrayBuffer()),
      progress: (amount) => console.log(`${amount}%:`)
      });
    • Overrides the IWorkbookIO.IBackingStore used by IWorkbookIO.write (and, in future, reads).

      Parameters

      • store: IBackingStore | null

        A backing store that owns persistence, or null to restore the built-in platform store.

      Returns void

      Use this to redirect where workbooks are persisted — for example a VSCode extension that posts bytes to the editor host, or a server/cloud store. The store receives a IWorkbookIO.WriteRequest (with a helper to encode the workbook) and returns the written IWorkbookIO.Origin handle, or null to signal cancellation.

      // Route every write through a host (e.g. a VSCode extension).
      workbookIO.setBackingStore({
      async write({ format, origin, encode }) {
      const bytes = await encode();
      await host.writeActiveDocument(bytes);
      return { format, origin, size: bytes.byteLength };
      }
      });
    • Writes a workbook via the configured IWorkbookIO.IBackingStore: a Save (no target — write back to the workbook's own origin) or an Export (an explicit target — write a copy; the workbook's origin is untouched).

      Type Parameters

      Parameters

      • workbook: IWorkbook

        The workbook instance to write.

      • Optionaltarget: string | IWorkbookIO.Origin | T

        An explicit destination — a file name/path or an IWorkbookIO.Origin — for an export. Omit (or pass options in its place) for a save.

      • Optionaloptions: T

        Encoding options (format, progress).

      Returns Promise<IWorkbookIO.Origin | null>

      A promise resolving to the IWorkbookIO.Origin handle actually written — the workbook's own origin for a save, the target handle for an export, updated with the written size — or null if the operation was cancelled (e.g. the user dismissed a save dialog).

      Save (write(workbook)): the destination is the workbook's origin. A bound, writable origin is re-saved silently. An unbound or read-only origin makes the store resolve a destination (a save dialog in the browser; an error in bare Node) — and on success the IO layer fills that origin in place, so the next save is silent. The rule: the store fills in a handle it resolved itself; it never overrides a handle the caller supplied.

      Export (write(workbook, target)): writes a copy to the target. The workbook's origin — its identity — is never touched, and the export does not mark the workbook clean (IWorkbookIO.addCommitListener fires for saves only). Re-targeting a workbook ("Save As") is IWorkbookIO.writeAs — the explicit rebind verb.

      Replacing the store (via IWorkbookIO.setBackingStore) redirects writing entirely — e.g. a VSCode extension posting bytes to the editor host, or a CLI prompting in the terminal.

      If options.format is not provided, it is inferred from the destination's extension (the explicit target, else the workbook's origin). There is no implicit default.

      // Save — back to the workbook's origin (or resolve a destination if it has none).
      const details = await workbookIO.write(workbook);

      // Export — a copy to an explicit destination; the origin is untouched.
      const details = await workbookIO.write(workbook, 'copy.xlsx');

      // Export in a specific format.
      const details = await workbookIO.write(workbook, 'report.csv', { format: 'csv' });
    • Writes a workbook to an ArrayBuffer in the specified format.

      Type Parameters

      Parameters

      • workbook: IWorkbook

        The workbook instance to write

      • Optionaloptions: T

        Write configuration including format type and encoding options

      Returns Promise<ArrayBufferLike>

      A promise resolving to an ArrayBuffer containing the encoded workbook data

      This method produces raw binary data in the format type you specify (sxl, xlsx, csv, etc.). The source type is always ArrayBuffer - use this for:

      • In-memory operations
      • Custom upload logic
      • Further processing before saving
      • Specify via options.format (e.g., 'sxl', 'xlsx', 'csv')
      • If not provided, defaults to the first registered write format
      // Write as Excel format
      const buffer: ArrayBufferLike = await workbookIO.writeArrayBuffer(workbook, {
      format: 'xlsx'
      });

      // Write as CSV
      const csvBuffer: ArrayBufferLike = await workbookIO.writeArrayBuffer(workbook, {
      format: 'csv'
      });

      // Upload to server
      const buffer: ArrayBufferLike = await workbookIO.writeArrayBuffer(workbook, { format: 'xlsx' });
      await fetch('/api/upload', {
      method: 'POST',
      body: buffer
      });
    • Save As: re-target the workbook's identity to target, then save. On success the workbook's origin (and so its display name) follows the new destination; on cancel/failure the origin is restored — identity unchanged.

      Type Parameters

      Parameters

      Returns Promise<IWorkbookIO.Origin | null>

      A promise resolving to the workbook's (re-targeted) IWorkbookIO.Origin, or null if the operation was cancelled.

      This is the explicit rebind verb — the one origin re-target IWorkbookIO.write never performs. It composes re-target + save so the whole flow stays coherent: the store resolves / persists against the workbook's own (re-targeted) handle — keeping platform session state (e.g. a browser file handle cache) keyed to the one live handle — and the save path marks the workbook clean via IWorkbookIO.addCommitListener. Handle mutation authority sits in the IO/store layer (the same layer that fills a resolved destination in), which is why this lives here and not on the model or a wrapper object.

      "Write a copy without moving the identity" is IWorkbookIO.write with a target (an export), not this.