@sheetxl/io
Version:
IO - Import/Export Libraries for SheetXL.
410 lines (379 loc) • 13.7 kB
TypeScript
import { FetchArgs } from '@sheetxl/utils';
import { ICellRange } from '@sheetxl/sdk';
import { IWorkbook } from '@sheetxl/sdk';
import { ParseConfig } from 'papaparse';
import { TaskProgress } from '@sheetxl/utils';
import { UnparseConfig } from 'papaparse';
/**
* Wrapper object to explicitly indicate base64 string content.
*
* Use this interface to disambiguate base64 strings from URLs when
* the automatic detection might be ambiguous.
*
* @example
* ```typescript
* // Explicit base64 (no ambiguity)
* const source: ImportSource = {
* source: { base64: 'iVBORw0KGgoAAAANSUhEUgAAA...' },
* type: 'png'
* };
* ```
*/
export declare interface Base64Args {
/** The base64 encoded string content */
base64: string;
}
export declare class DefaultWorkbookIO {
private _readFormatTypes;
private _writeFormatType;
constructor(readFormatTypes?: ReadFormatType[], writeFormatType?: WriteFormatType[]);
/**
* Detects the source type from the provided source value.
* Returns the detected type or null if it cannot be determined.
*/
private _detectImportSourceType;
getReadFormats(): readonly ReadFormatType[];
getWriteFormats(): readonly WriteFormatType[];
getReadFormatTypeForKey(key: string): ReadFormatType | null;
getReadFormatTypeForExt(ext: string): ReadFormatType | null;
getReadFormatTypeForMimeType(mimeType: string): ReadFormatType | null;
getWriteFormatTypeForExt(ext: string): WriteFormatType | null;
getWriteFormatType(text: string): WriteFormatType | null;
/**
* A string array of all the mimeTYpes. Used for the input accept attribute.
* @returns - An array of strings for the input types.
*/
getAllReadFormatTypeAsString(): string[];
toArrayBuffer(workbook: IWorkbook, key: string, options?: WriteWorkbookOptions): Promise<ArrayBufferLike>;
protected _fromArrayBuffer(arrayBuffer: ArrayBufferLike, formatKey: string, options?: ReadWorkbookOptions): Promise<IWorkbook>;
/**
* Imports a workbook from various source types with automatic detection.
*
* This method provides a unified interface for importing workbooks from different
* source types including files, base64 strings, fetch URLs, array buffers, and streams.
* The source type is automatically detected based on the input value.
*
* @param options - Optional import configuration and callbacks
*
* @returns A promise that resolves to ImportResults containing the workbook, filename, and detected type
*
* @throws {Error} When the source type cannot be detected
* @throws {Error} When no appropriate import handler is available
* @throws {Error} When the import operation fails
*
* @remarks
* Source type detection rules:
* - Objects with `base64` property → base64 type
* - Objects with `input` property → fetch type (FetchArgs)
* - Strings starting with `data:` → base64 type
* - Strings starting with `http://` or `https://` → fetch type
* - Strings starting with `/`, `./`, `../` → fetch type
* - Other strings → fetch type (default)
* - File objects → file type
* - ArrayBuffer/TypedArrays → buffer type
* - ReadableStream → stream type (converted to buffer)
* - Functions → resolved then re-detected
* - Promises → resolved then re-detected
*/
read(options: ReadWorkbookOptions): Promise<WorkbookHandle>;
protected _fromFile(file: File, options?: ReadWorkbookOptions): Promise<WorkbookHandle>;
/**
* Exports to the local file system attempting to use the fileName provided. This will
* use the exportType to determine the export handler to use.
*
* @returns a Promise indicating success or failure.
*/
writeFile(fileName: string | null, workbook: IWorkbook, options?: WriteWorkbookOptions): Promise<boolean>;
}
/**
* Union type representing all possible input sources for workbook imports.
*
* @remarks
* This type is used to define the source of data for importing workbooks,
* allowing for various formats such as URLs, files, and raw binary data.
*/
export declare interface FormatType {
/**
* The key used to identify the type of import.
*/
key: string;
/**
* A description of the type of import.
*/
description?: string;
/**
* The mime type of the import.
*/
mimeType: string;
/**
* Tags that are used by the UI.
*/
tags?: string[];
/**
* Indicates if this is the default import type.
*
* @defaultValue false
*
* @remarks
* For import the default doesn't have any significance other than an indicator for the UI.
*/
isDefault?: boolean;
}
/**
* Import from CSV.
*
* @param buffer The arraybuffer to import from.
* @param options Options for CSVImport
* @returns A workbook model with a single sheet
*
* @remarks
* Creates a workbook with a single tab.
*/
export declare const fromBufferCSV: (buffer: ArrayBuffer, options?: ReadCSVOptions) => Promise<IWorkbook>;
export declare const fromBufferJSON: WorkbookFromHandler;
/**
* Creates a new workbook with values imported from an XLSX.
*
* @param buffer The ArrayBuffer to import.
* @param options Import options.
* @returns A Promise for an IWorkbook
*/
export declare const fromBufferXLSX: (buffer: ArrayBuffer, options?: ReadXLSXOptions) => Promise<IWorkbook>;
/**
* Union type representing all possible io source types.
*
* @remarks
* This type encompasses all the different ways data can be provided
* for import operations, from simple strings to complex stream objects.
*/
export declare type IOSource = string | File | ArrayBufferLike | ReadableStream<Uint8Array> | FetchArgs | Base64Args;
export declare namespace IOUtils {
export {
WINDOW_FILENAME_RESERVED_REGEX,
MAX_WORKBOOK_NAME_SIZE,
WINDOW_FILENAME_CHAR_RESERVED_REGEX,
isValidWindowsFilename,
relativePath
}
}
/**
* Returns a boolean indicating the the string name is a valid windows filename.
* @param input The string to validate.
*/
declare const isValidWindowsFilename: (input: string) => boolean;
declare const MAX_WORKBOOK_NAME_SIZE = 96;
export declare interface ReadCSVOptions extends ReadWorkbookOptions {
/**
* Options specific for setting values.
*/
setValuesOptions?: ICellRange.SetValuesOptions;
/**
* Options specific for csv parsing.
*
* @remarks
* CSV parse delegates to the excellent Papa Parse library.
*
* @see
* {@link https://www.papaparse.com/docs#config}
*/
papaParseConfig?: ParseConfig;
}
export declare interface ReadFormatType extends FormatType {
/**
* The file extensions that this type of import supports.
*/
exts: string[];
handler: WorkbookFromHandler;
}
export declare interface ReadWorkbookOptions extends TaskProgress {
/**
* The io source for reading. Can be a direct value, Promise, or function.
*/
source: IOSource | Promise<IOSource> | (() => IOSource | Promise<IOSource>);
/**
* Provide options to the workbook constructor.
*/
constructorOptions?: IWorkbook.ConstructorOptions;
/**
* Optional file type hint (extension, MIME type, or import key).
*
* Used for type detection when it cannot be inferred from the source.
* Examples: 'xlsx', 'csv', 'application/json', 'Excel'
*/
formatType?: string;
/**
* Optional human-readable name for the import.
*
* Used as a fallback filename and for display purposes.
* If not provided, a default name will be generated based on the source.
*/
name?: string;
/**
* Allows for different constructor arguments depending on the type of format detected.
*
* @remarks
* This will overwrite the options with the constructorOptions provided.
*/
typedConstructorOptions?: Record<string, IWorkbook.ConstructorOptions>;
}
export declare interface ReadXLSXOptions extends ReadWorkbookOptions {
password?: string;
}
/**
* Returns a single path string from the current folder and relative path.
* If relativePath is already absolute (including URLs with different domains), returns it as-is.
*/
declare const relativePath: (currentFolder: string, relativePath: string) => string;
/**
* Export to CSV.
*
* @param workbook The workbook model to export
* @param options Export options
* @returns A workbook model with a single sheet
*
* @remarks
* This only exports the activeTab.
*/
export declare const toBufferCSV: WorkbookToHandler;
export declare const toBufferJSON: WorkbookToHandler;
export declare const toBufferXLSX: WorkbookToHandler;
declare const WINDOW_FILENAME_CHAR_RESERVED_REGEX: RegExp;
declare const WINDOW_FILENAME_RESERVED_REGEX: RegExp;
/**
* Import for reading from an array into an IWorkbook.
*
* @param arrayBuffer The array buffer containing the workbook data.
* @param options Optional options for loading the workbook, such as format type and workbook options.
* @returns A promise that resolves to an IWorkbook instance.
*/
export declare type WorkbookFromHandler = (arrayBuffer: ArrayBufferLike, options?: Omit<ReadWorkbookOptions, 'source'>) => Promise<IWorkbook>;
/**
* Used for results that want to return a workbook instance with a title.
*/
export declare interface WorkbookHandle {
/**
* The workbook instance that was imported.
*/
workbook: IWorkbook;
/**
* The title of the workbook, if available.
*
* @remarks
* This can be null if no title was provided or could not be determined.
*/
title: string | null;
/**
* The import type of import detected.
*/
formatType: FormatType;
}
export declare const WorkbookIO: DefaultWorkbookIO;
/**
* Export for writing to an array from an IWorkbook
*
* @param workbook The workbook instance to export.
* @param options Optional options for saving the workbook, such as compression and whitespace formatting.
* @returns A promise that resolves to an array buffer representing the workbook
*/
export declare type WorkbookToHandler = (workbook: IWorkbook, options?: Omit<WriteWorkbookOptions, 'source'>) => Promise<ArrayBufferLike>;
/**
* Options for exporting to CSV file format.
*
* @remarks
* The default options mimic Excel 2024.
*/
export declare interface WriteCSVOptions extends WriteWorkbookOptions {
/**
* Indicate whether hidden columns and rows are skipped in the CSV output.
* @defaultValue false
*/
excludeHidden?: boolean;
/**
* Indicates whether the leading blank rows should be trimmed.
*
* @defaultValue false
*/
trimLeadingBlankRow?: boolean;
/**
* Indicates whether the leading blank columns should be trimmed.
*
* @defaultValue true
*/
trimLeadingBlankColumn?: boolean;
/**
* Specify the tab to export.
*
* @remarks
*
* CSV Will only export one tab. By default this is the active tab. To change this pass a SheetKey.
*
* @defaultValue 'the current active tab'
*/
sheetKey?: string | number;
/**
* configuration for csv export
*
* @remarks
*
* CSV parse delegates to the excellent Papa Parse library.
* All options are exposes via papParseConfig.
*
* @see
* {@link https://www.papaparse.com/docs#unparse-config-default}
*
*/
papaParseConfig?: UnparseConfig;
}
/**
* Defines the format type for saving a workbook.
*
* @remarks
* This interface extends {@link FormatType} to include additional properties
* specific to saving formats, such as file extension and export handler.
*/
export declare interface WriteFormatType extends FormatType {
ext: string;
handler: WorkbookToHandler;
}
export declare interface WriteJSONOptions extends WriteWorkbookOptions {
/**
* If set to a number then JSON will add white space to make the JSON more human readable.
*
* @defaultValue - `2` in dev and `0` in prod
*
* @remarks
* Setting this to a non `0` values maybe greatly increase the JSON size.
*/
whiteSpace?: number;
/**
* If implemented called after json and before serializing.
*
* @remarks
* Any changes made to the json will be serialized.
*/
beforeWrite?(source: IWorkbook, json: IWorkbook.JSON): void;
/**
* Indicates if file should be compressed using gzip.
*
* @defaultValue - 'false' in 'dev' and 'true' in 'prod'
*/
compress?: boolean;
}
export declare interface WriteWorkbookOptions {
/**
* The destination for writing the workbook.
*
* Can be a string (file path), File, Blob, or a function returning these types.
*/
/**
* Optional file type hint (extension, MIME type, or export key).
*
* Used for type detection when it cannot be inferred from the destination.
* Examples: 'xlsx', 'csv', 'application/json', 'Excel'
*/
formatType?: string;
}
export declare interface WriteXLSXOptions extends WriteWorkbookOptions {
password?: string;
}
export { }