google-spreadsheet
Version:
Google Sheets API -- simple interface to read/write data and manage sheets
1,572 lines • 69.9 kB
text/typescript
import * as node_stream_web0 from "node:stream/web";
import { KyInstance, RetryOptions } from "ky";
import { ReadableStream as ReadableStream$1 } from "stream/web";
//#region src/lib/GoogleSpreadsheetRow.d.ts
declare class GoogleSpreadsheetRow<T extends Record<string, any> = Record<string, any>> {
/** parent GoogleSpreadsheetWorksheet instance */
readonly _worksheet: GoogleSpreadsheetWorksheet;
/** the A1 row (1-indexed) */
private _rowNumber;
/** raw underlying data for row */
private _rawData;
constructor(/** parent GoogleSpreadsheetWorksheet instance */
_worksheet: GoogleSpreadsheetWorksheet, /** the A1 row (1-indexed) */
_rowNumber: number, /** raw underlying data for row */
_rawData: any[]);
/** pad _rawData with empty strings so it always matches header length */
private _padRawData;
private _deleted;
get deleted(): boolean;
/** row number (matches A1 notation, ie first row is 1) */
get rowNumber(): number;
/**
* @internal
* Used internally to update row numbers after deleting rows.
* Should not be called directly.
*/
_updateRowNumber(newRowNumber: number): void;
/**
* @internal
* Used internally to mark row as deleted.
* Should not be called directly.
*/
_markDeleted(): void;
get a1Range(): string;
/** get row's value of specific cell (by header key) */
get(key: keyof T): any;
/** set row's value of specific cell (by header key) */
set<K extends keyof T>(key: K, val: T[K]): void;
/** set multiple values in the row at once from an object */
assign(obj: Partial<T>): void;
/** return raw object of row data */
toObject(): Partial<T>;
/** save row values */
save(options?: {
raw?: boolean;
}): Promise<void>;
/** delete this row */
delete(): Promise<any>;
/**
* @internal
* Used internally to clear row data after calling sheet.clearRows
* Should not be called directly.
*/
_clearRowData(): void;
}
//#endregion
//#region src/lib/types/util-types.d.ts
type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> & Partial<Pick<Type, Key>>;
type RecursivePartial<T> = { [P in keyof T]?: RecursivePartial<T[P]> };
//#endregion
//#region src/lib/types/sheets-types.d.ts
type Integer = number;
type SpreadsheetId = string;
type WorksheetId = number;
type DataSourceId = string;
type WorksheetIndex = number;
type RowOrColumnIndex = number;
type RowIndex = number;
type ColumnIndex = number;
type A1Address = string;
type A1Range = string;
type NamedRangeId = string;
/**
* ISO language code
* @example en
* @example en_US
* */
type LocaleCode = string;
/**
* timezone code, if not recognized, may be a custom time zone such as `GMT-07:00`
* @example America/New_York
* */
type Timezone = string;
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#SheetType */
type WorksheetType = /** The sheet is a grid. */'GRID' | /** The sheet has no grid and instead has an object like a chart or image. */'OBJECT' | /** The sheet connects with an external DataSource and shows the preview of data. */'DATA_SOURCE';
type WorksheetDimension = 'ROWS' | 'COLUMNS';
type HyperlinkDisplayType = 'LINKED' | 'PLAIN_TEXT';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#numberformattype */
type NumberFormatType = /** Text formatting, e.g 1000.12 */'TEXT' | /** Number formatting, e.g, 1,000.12 */'NUMBER' | /** Percent formatting, e.g 10.12% */'PERCENT' | /** Currency formatting, e.g $1,000.12 */'CURRENCY' | /** Date formatting, e.g 9/26/2008 */'DATE' | /** Time formatting, e.g 3:59:00 PM */'TIME' | /** Date+Time formatting, e.g 9/26/08 15:59:00 */'DATE_TIME' | /** Scientific number formatting, e.g 1.01E+03 */'SCIENTIFIC';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#errortype */
type CellValueErrorType = /** Corresponds to the #ERROR! error */'ERROR' | /** Corresponds to the #NULL! error. */'NULL_VALUE' | /** Corresponds to the #DIV/0 error. */'DIVIDE_BY_ZERO' | /** Corresponds to the #VALUE! error. */'VALUE' | /** Corresponds to the #REF! error. */'REF' | /** Corresponds to the #NAME? error. */'NAME' | /** Corresponds to the #NUM! error. */'NUM' | /** Corresponds to the #N/A error. */'N_A' | /** Corresponds to the Loading... state. */'LOADING';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#horizontalalign */
type HorizontalAlign = 'LEFT' | 'CENTER' | 'RIGHT';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#verticalalign */
type VerticalAlign = 'TOP' | 'MIDDLE' | 'BOTTOM';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#textdirection */
type TextDirection = 'LEFT_TO_RIGHT' | 'RIGHT_TO_LEFT';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#wrapstrategy */
type WrapStrategy = 'OVERFLOW_CELL' | 'LEGACY_WRAP' | 'CLIP' | 'WRAP';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#themecolortype */
type ThemeColorType = 'TEXT' | 'BACKGROUND' | 'ACCENT1' | 'ACCENT2' | 'ACCENT3' | 'ACCENT4' | 'ACCENT5' | 'ACCENT6' | 'LINK';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#recalculationinterval */
type RecalculationInterval = 'ON_CHANGE' | 'MINUTE' | 'HOUR';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata#developermetadatavisibility */
type DeveloperMetadataVisibility = /** Document-visible metadata is accessible from any developer project with access to the document. */'DOCUMENT' /** Project-visible metadata is only visible to and accessible by the developer project that created the metadata. */ | 'PROJECT';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata#developermetadatalocationtype */
type DeveloperMetadataLocationType = 'ROW' | 'COLUMN' | 'SHEET' | 'SPREADSHEET';
type TextFormat = {
foregroundColor?: Color;
foregroundColorStyle?: ColorStyle;
fontFamily?: string;
fontSize?: number;
bold?: boolean;
italic?: boolean;
strikethrough?: boolean;
underline?: boolean;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#Style */
type CellBorderLineStyle = 'NONE' | 'DOTTED' | 'DASHED' | 'SOLID' | 'SOLID_MEDIUM' | 'SOLID_THICK' | 'DOUBLE';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#Border */
type CellBorder = {
style: CellBorderLineStyle;
width: number;
color: Color;
colorStyle: ColorStyle;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#Borders */
type CellBorders = {
top: CellBorder;
bottom: CellBorder;
left: CellBorder;
right: CellBorder;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#Padding */
type CellPadding = {
top: number;
bottom: number;
left: number;
right: number;
};
type TextRotation = {
angle: number;
vertical: boolean;
};
type DimensionRangeIndexes = {
startIndex: RowOrColumnIndex;
endIndex: RowOrColumnIndex;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata#DeveloperMetadata.DeveloperMetadataLocation */
interface DeveloperMetadataLocation {
sheetId?: number;
spreadsheet?: boolean;
dimensionRange?: DimensionRange;
locationType?: DeveloperMetadataLocationType;
}
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata#DeveloperMetadata.DeveloperMetadataLocation */
interface DeveloperMetadata {
metadataId?: number;
metadataKey: string;
metadataValue?: string;
location?: DeveloperMetadataLocation;
visibility?: DeveloperMetadataVisibility;
}
interface WorksheetDimensionProperties {
pixelSize: number;
hiddenByUser: boolean;
hiddenByFilter: boolean;
/**
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata#DeveloperMetadata
*/
developerMetadata: DeveloperMetadata[];
}
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#DataSourceColumnReference */
type DataSourceColumnReference = {
name: string;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#DataSourceColumn */
type DataSourceColumn = {
reference: DataSourceColumnReference;
formula: string;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#DataExecutionState */
type DataExecutionState = /** The data execution has not started. */'NOT_STARTED' | /** The data execution has started and is running. */'RUNNING' | /** The data execution has completed successfully. */'SUCCEEDED' | /** The data execution has completed with errors. */'FAILED';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#DataExecutionState */
type DataExecutionErrorCode = /** Default value, do not use. */'DATA_EXECUTION_ERROR_CODE_UNSPECIFIED' | /** The data execution timed out. */'TIMED_OUT' | /** The data execution returns more rows than the limit. */'TOO_MANY_ROWS' | /** The data execution returns more columns than the limit. */'TOO_MANY_COLUMNS' | /** The data execution returns more cells than the limit. */'TOO_MANY_CELLS' | /** Error is received from the backend data execution engine (e.g. BigQuery). Check errorMessage for details. */'ENGINE' | /** One or some of the provided data source parameters are invalid. */'PARAMETER_INVALID' | /** The data execution returns an unsupported data type. */'UNSUPPORTED_DATA_TYPE' | /** The data execution returns duplicate column names or aliases. */'DUPLICATE_COLUMN_NAMES' | /** The data execution is interrupted. Please refresh later. */'INTERRUPTED' | /** The data execution is currently in progress, can not be refreshed until it completes. */'CONCURRENT_QUERY' | /** Other errors. */'OTHER' | /** The data execution returns values that exceed the maximum characters allowed in a single cell. */'TOO_MANY_CHARS_PER_CELL' | /** The database referenced by the data source is not found. */'DATA_NOT_FOUND' | /** The user does not have access to the database referenced by the data source. */'PERMISSION_DENIED' | /** The data execution returns columns with missing aliases. */'MISSING_COLUMN_ALIAS' | /** The data source object does not exist. */'OBJECT_NOT_FOUND' | /** The data source object is currently in error state. To force refresh, set force in RefreshDataSourceRequest . */'OBJECT_IN_ERROR_STATE' | /** The data source object specification is invalid. */'OBJECT_SPEC_INVALID';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#DataExecutionStatus */
type DataExecutionStatus = {
'state': DataExecutionState;
'errorCode': DataExecutionErrorCode;
'errorMessage': string;
'lastRefreshTime': string;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#DataSourceSheetProperties */
type DataSourceSheetProperties = {
'dataSourceId': DataSourceId;
'columns': DataSourceColumn[];
'dataExecutionStatus': DataExecutionStatus;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#SpreadsheetProperties */
type SpreadsheetProperties = {
/** title of the spreadsheet */title: string; /** locale of the spreadsheet (note - not all locales are supported) */
locale: LocaleCode; /** amount of time to wait before volatile functions are recalculated */
autoRecalc: RecalculationInterval; /** timezone of the sheet */
timeZone: Timezone;
defaultFormat: any;
iterativeCalculationSettings: any;
spreadsheetTheme: any;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#SheetProperties */
type WorksheetProperties = {
'sheetId': WorksheetId;
'title': string;
'index': WorksheetIndex;
'sheetType': WorksheetType;
'gridProperties': WorksheetGridProperties;
'hidden': boolean;
'tabColor': Color;
'tabColorStyle': ColorStyle;
'rightToLeft': boolean;
'dataSourceSheetProperties': DataSourceSheetProperties;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#CellFormat */
type CellFormat = {
/** format describing how number values should be represented to the user */numberFormat: NumberFormat; /** @deprecated use backgroundColorStyle */
backgroundColor: Color;
backgroundColorStyle: ColorStyle;
borders: CellBorders;
padding: CellPadding;
horizontalAlignment: HorizontalAlign;
verticalAlignment: VerticalAlign;
wrapStrategy: WrapStrategy;
textDirection: TextDirection;
textFormat: TextFormat;
hyperlinkDisplayType: HyperlinkDisplayType;
textRotation: TextRotation;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#numberformat */
type NumberFormat = {
type: NumberFormatType;
/**
* pattern string used for formatting
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#numberformat
* */
pattern: string;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#GridProperties */
type WorksheetGridProperties = {
rowCount: number;
columnCount: number;
frozenRowCount?: number;
frozenColumnCount?: number;
hideGridlines?: boolean;
rowGroupControlAfter?: boolean;
columnGroupControlAfter?: boolean;
};
/**
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/DimensionRange
*/
type DimensionRange = {
sheetId: WorksheetId;
dimension: WorksheetDimension;
startIndex?: Integer;
endIndex?: Integer;
};
/**
* object describing a range in a sheet
* see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#GridRange
* */
type GridRange = {
/** The sheet this range is on */sheetId: WorksheetId; /** The start row (inclusive) of the range, or not set if unbounded. */
startRowIndex?: Integer; /** The end row (exclusive) of the range, or not set if unbounded. */
endRowIndex?: Integer; /** The start column (inclusive) of the range, or not set if unbounded. */
startColumnIndex?: Integer; /** The end column (exclusive) of the range, or not set if unbounded. */
endColumnIndex?: Integer;
};
type GridRangeWithoutWorksheetId = Omit<GridRange, 'sheetId'>;
type GridRangeWithOptionalWorksheetId = MakeOptional<GridRange, 'sheetId'>;
type DataFilter = A1Range | GridRange | DataFilterObject;
type DataFilterWithoutWorksheetId = A1Range | GridRangeWithoutWorksheetId | DataFilterObject;
/**
* A coordinate in a sheet. All indexes are zero-based.
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#GridCoordinate
*/
type GridCoordinate = {
/** The sheet this coordinate is on */sheetId: WorksheetId; /** The row index of the coordinate */
rowIndex: RowIndex; /** The column index of the coordinate */
columnIndex: ColumnIndex;
};
type GridCoordinateWithOptionalWorksheetId = MakeOptional<GridCoordinate, 'sheetId'>;
/**
* How a paste operation should be applied.
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#PasteType
*/
type PasteType = 'PASTE_NORMAL' | 'PASTE_VALUES' | 'PASTE_FORMAT' | 'PASTE_NO_BORDERS' | 'PASTE_FORMULA' | 'PASTE_DATA_VALIDATION' | 'PASTE_CONDITIONAL_FORMATTING';
/**
* How pasted data should be oriented.
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#PasteOrientation
*/
type PasteOrientation = 'NORMAL' | 'TRANSPOSE';
/**
* The delimiter type for text to columns operations.
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DelimiterType
*/
type DelimiterType = 'DELIMITER_TYPE_UNSPECIFIED' | 'COMMA' | 'SEMICOLON' | 'PERIOD' | 'SPACE' | 'CUSTOM' | 'AUTODETECT';
/**
* The order data should be sorted.
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#sortorder
*/
type SortOrder = 'SORT_ORDER_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
/**
* A sort order specification for a single column.
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#sortspec
*/
type SortSpec = {
/** The dimension (column index) to sort by */dimensionIndex: Integer; /** The order data should be sorted */
sortOrder?: SortOrder; /** Background color to sort by - cells with this color are sorted to the top */
backgroundColorStyle?: any; /** Foreground color to sort by - cells with this color are sorted to the top */
foregroundColorStyle?: any;
};
/**
* Source and destination areas for autofill operations.
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#SourceAndDestination
*/
type SourceAndDestination = {
/** The source range to autofill from (sheetId optional) */source: GridRangeWithOptionalWorksheetId; /** The dimension that data should be filled in */
dimension: WorksheetDimension; /** The number of rows or columns to fill (positive = after, negative = before) */
fillLength: Integer;
};
/**
* object describing the editors of a protected range
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#Editors
* */
type Editors = {
/** The email addresses of users with edit access to the protected range. */users?: string[]; /** The email addresses of groups with edit access to the protected range. */
groups?: string[]; /** True if anyone in the document's domain has edit access to the protected range. */
domainUsersCanEdit?: boolean;
};
/**
* object describing a protected range in a sheet
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#ProtectedRange
* */
type ProtectedRange = {
/** The ID of the protected range - read-only, auto-assigned */protectedRangeId?: Integer; /** The range that is being protected - mutually exclusive with namedRangeId */
range?: GridRange; /** The named range this protected range is backed by - mutually exclusive with range */
namedRangeId?: NamedRangeId; /** The description of this protected range */
description?: string; /** True if this protected range will show a warning when editing. When true, editors is ignored. */
warningOnly?: boolean; /** True if the user who requested this protected range can edit the protected area - read-only */
requestingUserCanEdit?: boolean; /** The list of unprotected ranges within a protected sheet. Only supported on protected sheets. */
unprotectedRanges?: GridRange[]; /** The users and groups with edit access to the protected range. Not supported with warningOnly. */
editors?: Editors;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#colorstyle */
type ColorStyle = {
rgbColor: Color;
} | {
themeColor: ThemeColorType;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#Color */
type Color = {
red: number;
green: number;
blue: number; /** docs say alpha is not generally supported? */
alpha?: number;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption */
type ValueRenderOption = /** Values will be calculated & formatted in the reply according to the cell's formatting. Formatting is based on the spreadsheet's locale, not the requesting user's locale. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return "$1.23". */'FORMATTED_VALUE' | /** Values will be calculated, but not formatted in the reply. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return the number 1.23. */'UNFORMATTED_VALUE' | /** Values will not be calculated. The reply will include the formulas. For example, if A1 is 1.23 and A2 is =A1 and formatted as currency, then A2 would return "=A1". */'FORMULA';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#query-parameters */
type GetValuesRequestOptions = {
majorDimension?: WorksheetDimension;
valueRenderOption?: ValueRenderOption;
};
/**
* Info about an error in a cell
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#errortype
*/
type ErrorValue = {
type: CellValueErrorType;
message: string;
};
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#ExtendedValue */
type ExtendedValue = {
numberValue: number;
} | {
stringValue: string;
} | {
boolValue: boolean;
} | {
formulaValue: string;
} | {
errorValue: ErrorValue;
};
type CellValueType = 'boolValue' | 'stringValue' | 'numberValue' | 'errorValue';
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells */
type CellData = {
/** The value the user entered in the cell. e.g., 1234, 'Hello', or =NOW() Note: Dates, Times and DateTimes are represented as doubles in serial number format. */userEnteredValue: ExtendedValue; /** The effective value of the cell. For cells with formulas, this is the calculated value. For cells with literals, this is the same as the userEnteredValue. This field is read-only. */
effectiveValue: ExtendedValue; /** The formatted value of the cell. This is the value as it's shown to the user. This field is read-only. */
formattedValue: string; /** The format the user entered for the cell. */
userEnteredFormat: CellFormat; /** The effective format being used by the cell. This includes the results of applying any conditional formatting and, if the cell contains a formula, the computed number format. If the effective format is the default format, effective format will not be written. This field is read-only. */
effectiveFormat: CellFormat; /** hyperlink in the cell if any */
hyperlink?: string; /** note on the cell */
note?: string;
};
/** shape of the cell data sent back when fetching the sheet */
type CellDataRange = {
startRow?: RowIndex;
startColumn?: ColumnIndex;
rowMetadata: any[];
columnMetadata: any[];
rowData: {
values: any[];
}[];
};
type AddRowOptions = {
/** set to true to use raw mode rather than user entered */raw?: boolean; /** set to true to insert new rows in the sheet while adding this data */
insert?: boolean;
};
/**
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#ConditionType
*/
type ConditionType = 'NUMBER_GREATER' | 'NUMBER_GREATER_THAN_EQ' | 'NUMBER_LESS' | 'NUMBER_LESS_THAN_EQ' | 'NUMBER_EQ' | 'NUMBER_NOT_EQ' | 'NUMBER_BETWEEN' | 'NUMBER_NOT_BETWEEN' | 'TEXT_CONTAINS' | 'TEXT_NOT_CONTAINS' | 'TEXT_STARTS_WITH' | 'TEXT_ENDS_WITH' | 'TEXT_EQ' | 'TEXT_IS_EMAIL' | 'TEXT_IS_URL' | 'DATE_EQ' | 'DATE_BEFORE' | 'DATE_AFTER' | 'DATE_ON_OR_BEFORE' | 'DATE_ON_OR_AFTER' | 'DATE_BETWEEN' | 'DATE_NOT_BETWEEN' | 'DATE_IS_VALID' | 'ONE_OF_RANGE' | 'ONE_OF_LIST' | 'BLANK' | 'NOT_BLANK' | 'CUSTOM_FORMULA' | 'BOOLEAN' | 'TEXT_NOT_EQ' | 'DATE_NOT_EQ' | 'FILTER_EXPRESSION';
/**
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#relativedate
*/
type RelativeDate = 'PAST_YEAR' | 'PAST_MONTH' | 'PAST_WEEK' | 'YESTERDAY' | 'TODAY' | 'TOMORROW';
/**
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#ConditionValue
*/
type ConditionValue = {
relativeDate: RelativeDate;
userEnteredValue?: undefined;
} | {
relativeDate?: undefined;
userEnteredValue: string;
};
/**
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#BooleanCondition
*/
type BooleanCondition = {
/** The type of condition. */type: ConditionType;
/**
* The values of the condition.
* The number of supported values depends on the condition type. Some support zero values, others one or two values, and ConditionType.ONE_OF_LIST supports an arbitrary number of values.
*/
values: ConditionValue[];
};
/**
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#DataValidationRule
*
* example:
* - https://stackoverflow.com/a/43442775/3068233
*/
type DataValidationRule = {
/** The condition that data in the cell must match. */condition: BooleanCondition; /** A message to show the user when adding data to the cell. */
inputMessage?: string; /** True if invalid data should be rejected. */
strict: boolean; /** True if the UI should be customized based on the kind of condition. If true, "List" conditions will show a dropdown. */
showCustomUi: boolean;
};
/**
* Filtering specification for a column
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#FilterSpec
*/
type FilterSpec = {
/** The column index */columnIndex?: Integer; /** The filter criteria */
filterCriteria?: BooleanCondition; /** The reference to the data source column (for data source sheets) */
dataSourceColumnReference?: any;
};
/**
* A filter view in a sheet
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#FilterView
*/
type FilterView = {
/** The ID of the filter view */filterViewId?: Integer; /** The name of the filter view */
title?: string; /** The range this filter view covers */
range?: GridRange; /** The named range this filter view is backed by (mutually exclusive with range) */
namedRangeId?: string; /** The table this filter view is backed by (mutually exclusive with range) */
tableId?: string; /** The sort order per column */
sortSpecs?: SortSpec[]; /** The criteria for showing/hiding values per column (deprecated, use filterSpecs) */
criteria?: Record<string, BooleanCondition>; /** The filter specifications per column */
filterSpecs?: FilterSpec[];
};
/**
* A rule describing a conditional format
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#ConditionalFormatRule
*/
type ConditionalFormatRule = {
/** The ranges that are formatted if the condition is true */ranges?: GridRange[]; /** The formatting is either 'on' or 'off' according to the rule */
booleanRule?: BooleanRule; /** The formatting will vary based on the gradients in the rule */
gradientRule?: GradientRule;
};
/**
* A rule that may or may not match, depending on the condition
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#BooleanRule
*/
type BooleanRule = {
/** The condition of the rule */condition: BooleanCondition; /** The format to apply (partial format supported) */
format: Partial<CellFormat>;
};
/**
* A rule that applies a gradient color scale format
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#GradientRule
*/
type GradientRule = {
/** The starting point for the gradient */minpoint: InterpolationPoint; /** The midway point for the gradient (optional) */
midpoint?: InterpolationPoint; /** The final point for the gradient */
maxpoint: InterpolationPoint;
};
/**
* A single interpolation point on a gradient
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#InterpolationPoint
*/
type InterpolationPoint = {
/** The color to use at this point */color?: Color; /** The color style to use at this point */
colorStyle?: ColorStyle; /** How to calculate the value that this interpolation point uses */
type?: InterpolationPointType; /** The value this interpolation point uses */
value?: string;
};
/**
* The type of interpolation point
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#interpolationpointtype
*/
type InterpolationPointType = 'MIN' | 'MAX' | 'NUMBER' | 'PERCENT' | 'PERCENTILE';
/**
* Properties for row or column bands
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#BandingProperties
*/
type BandingProperties = {
/** The color of the first row/column (takes priority over band colors) */headerColorStyle?: ColorStyle; /** The color of the last row/column */
footerColorStyle?: ColorStyle; /** The first color that is alternating (required) */
firstBandColorStyle?: ColorStyle; /** The second color that is alternating (required) */
secondBandColorStyle?: ColorStyle;
};
/**
* A banded (alternating colors) range in a sheet
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#BandedRange
*/
type BandedRange = {
/** The id of the banded range */bandedRangeId?: Integer; /** The range over which these properties are applied */
range?: GridRange; /** Properties for row banding */
rowProperties?: BandingProperties; /** Properties for column banding */
columnProperties?: BandingProperties;
};
/**
* Strategy for matching developer metadata locations
* @see https://developers.google.com/sheets/api/reference/rest/v4/DataFilter#DeveloperMetadataLookup.DeveloperMetadataLocationMatchingStrategy
*/
type DeveloperMetadataLocationMatchingStrategy = 'DEVELOPER_METADATA_LOCATION_MATCHING_STRATEGY_UNSPECIFIED' | 'EXACT_LOCATION' | 'INTERSECTING_LOCATION';
/**
* Filter for matching developer metadata
* @see https://developers.google.com/sheets/api/reference/rest/v4/DataFilter#DeveloperMetadataLookup
*/
type DeveloperMetadataLookup = {
/** Determines how location matching is performed */locationType?: DeveloperMetadataLocationType; /** Limits the selected metadata to that which has a matching location */
metadataLocation?: DeveloperMetadataLocation; /** Determines how location matching is done */
locationMatchingStrategy?: DeveloperMetadataLocationMatchingStrategy; /** Limits the selected metadata to that which has a matching metadata ID */
metadataId?: Integer; /** Limits the selected metadata to that which has a matching metadata key */
metadataKey?: string; /** Limits the selected metadata to that which has a matching metadata value */
metadataValue?: string; /** Limits the selected metadata to that which has a matching visibility */
visibility?: DeveloperMetadataVisibility;
};
/**
* Filter that describes what data should be selected or returned
* @see https://developers.google.com/sheets/api/reference/rest/v4/DataFilter
*/
type DataFilterObject = {
/** Selects data associated with the developer metadata matching the criteria */developerMetadataLookup?: DeveloperMetadataLookup; /** Selects data that matches the specified A1 range */
a1Range?: A1Range; /** Selects data that matches the range */
gridRange?: GridRange;
};
//#endregion
//#region src/lib/GoogleSpreadsheetCellErrorValue.d.ts
/**
* Cell error
*
* not a js "error" that gets thrown, but a value that holds an error code and message for a cell
* it's useful to use a class so we can check `instanceof`
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#ErrorType
*/
declare class GoogleSpreadsheetCellErrorValue {
/**
* type of the error
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#ErrorType
* */
readonly type: CellValueErrorType;
/** A message with more information about the error (in the spreadsheet's locale) */
readonly message: string;
constructor(rawError: ErrorValue);
}
//#endregion
//#region src/lib/GoogleSpreadsheetCell.d.ts
declare class GoogleSpreadsheetCell {
readonly _sheet: GoogleSpreadsheetWorksheet;
private _rowIndex;
private _columnIndex;
private _rawData?;
private _draftData;
private _error?;
private _deleted;
constructor(_sheet: GoogleSpreadsheetWorksheet, _rowIndex: RowIndex, _columnIndex: ColumnIndex, rawCellData: CellData);
get deleted(): boolean;
/**
* update cell using raw CellData coming back from sheets API
* @internal
*/
_updateRawData(newData: CellData): void;
get rowIndex(): number;
get columnIndex(): number;
get a1Column(): string;
get a1Row(): number;
get a1Address(): string;
/**
* @internal
* Used internally to update cell indices after deleting rows/columns.
* Should not be called directly.
*/
_updateIndices(rowIndex: RowIndex, columnIndex: ColumnIndex): void;
/**
* @internal
* Used internally to mark cell as deleted.
* Should not be called directly.
*/
_markDeleted(): void;
get value(): number | boolean | string | null | GoogleSpreadsheetCellErrorValue;
set value(newValue: number | boolean | Date | string | null | undefined | GoogleSpreadsheetCellErrorValue);
get valueType(): CellValueType | null;
/** The formatted value of the cell - this is the value as it's shown to the user */
get formattedValue(): string | null;
get formula(): string | null;
set formula(newValue: string | null);
/**
* @deprecated use `cell.errorValue` instead
*/
get formulaError(): GoogleSpreadsheetCellErrorValue | undefined;
/**
* error contained in the cell, which can happen with a bad formula (maybe some other weird cases?)
*/
get errorValue(): GoogleSpreadsheetCellErrorValue | undefined;
get numberValue(): number | undefined;
set numberValue(val: number | undefined);
get boolValue(): boolean | undefined;
set boolValue(val: boolean | undefined);
get stringValue(): string | undefined;
set stringValue(val: string | undefined);
/**
* Hyperlink contained within the cell.
*
* To modify, do not set directly. Instead set cell.formula, for example `cell.formula = \'=HYPERLINK("http://google.com", "Google")\'`
*/
get hyperlink(): string | undefined;
/** a note attached to the cell */
get note(): string;
set note(newVal: string | null | undefined | false);
get userEnteredFormat(): Readonly<CellFormat | undefined>;
get effectiveFormat(): Readonly<CellFormat | undefined>;
private _getFormatParam;
private _setFormatParam;
get numberFormat(): CellFormat["numberFormat"];
get backgroundColor(): CellFormat["backgroundColor"];
get backgroundColorStyle(): CellFormat["backgroundColorStyle"];
get borders(): CellFormat["borders"];
get padding(): CellFormat["padding"];
get horizontalAlignment(): CellFormat["horizontalAlignment"];
get verticalAlignment(): CellFormat["verticalAlignment"];
get wrapStrategy(): CellFormat["wrapStrategy"];
get textDirection(): CellFormat["textDirection"];
get textFormat(): CellFormat["textFormat"];
get hyperlinkDisplayType(): CellFormat["hyperlinkDisplayType"];
get textRotation(): CellFormat["textRotation"];
set numberFormat(newVal: CellFormat['numberFormat']);
set backgroundColor(newVal: CellFormat['backgroundColor']);
set backgroundColorStyle(newVal: CellFormat['backgroundColorStyle']);
set borders(newVal: CellFormat['borders']);
set padding(newVal: CellFormat['padding']);
set horizontalAlignment(newVal: CellFormat['horizontalAlignment']);
set verticalAlignment(newVal: CellFormat['verticalAlignment']);
set wrapStrategy(newVal: CellFormat['wrapStrategy']);
set textDirection(newVal: CellFormat['textDirection']);
set textFormat(newVal: CellFormat['textFormat']);
set hyperlinkDisplayType(newVal: CellFormat['hyperlinkDisplayType']);
set textRotation(newVal: CellFormat['textRotation']);
clearAllFormatting(): void;
get _isDirty(): boolean;
discardUnsavedChanges(): void;
/**
* saves updates for single cell
* usually it's better to make changes and call sheet.saveUpdatedCells
* */
save(): Promise<void>;
/**
* used by worksheet when saving cells
* returns an individual batchUpdate request to update the cell
* @internal
*/
_getUpdateRequest(): {
updateCells: {
rows: {
values: any[];
}[];
fields: string;
start: {
sheetId: number;
rowIndex: number;
columnIndex: number;
};
};
} | null;
}
//#endregion
//#region src/lib/GoogleSpreadsheetWorksheet.d.ts
type RowCellData = string | number | boolean | Date;
type RawRowData = RowCellData[] | Record<string, RowCellData>;
declare class GoogleSpreadsheetWorksheet {
/** parent GoogleSpreadsheet instance */
readonly _spreadsheet: GoogleSpreadsheet;
private _headerRowIndex;
private _rawProperties;
private _cells;
private _rowMetadata;
private _columnMetadata;
private _protectedRanges;
private _headerValues;
get headerValues(): string[];
constructor(/** parent GoogleSpreadsheet instance */
_spreadsheet: GoogleSpreadsheet, rawProperties: WorksheetProperties, rawCellData?: CellDataRange[], protectedRanges?: ProtectedRange[]);
updateRawData(properties: WorksheetProperties, rawCellData: CellDataRange[], protectedRanges?: ProtectedRange[]): void;
_makeSingleUpdateRequest(requestType: string, requestParams: any): Promise<any>;
private _ensureInfoLoaded;
/**
* clear local cache of sheet data/properties
*/
resetLocalCache(/** set to true to clear data only, leaving sheet metadata/propeties intact */
dataOnly?: boolean): void;
private _fillCellData;
private _addSheetIdToRange;
private _getProp;
private _setProp;
get sheetId(): WorksheetProperties["sheetId"];
get title(): WorksheetProperties["title"];
get index(): WorksheetProperties["index"];
get sheetType(): WorksheetProperties["sheetType"];
get gridProperties(): WorksheetProperties["gridProperties"];
get hidden(): WorksheetProperties["hidden"];
get tabColor(): WorksheetProperties["tabColor"];
get rightToLeft(): WorksheetProperties["rightToLeft"];
get protectedRanges(): ProtectedRange[] | null;
private get _headerRange();
set sheetId(newVal: WorksheetProperties['sheetId']);
set title(newVal: WorksheetProperties['title']);
set index(newVal: WorksheetProperties['index']);
set sheetType(newVal: WorksheetProperties['sheetType']);
set gridProperties(newVal: WorksheetProperties['gridProperties']);
set hidden(newVal: WorksheetProperties['hidden']);
set tabColor(newVal: WorksheetProperties['tabColor']);
set rightToLeft(newVal: WorksheetProperties['rightToLeft']);
get rowCount(): number;
get columnCount(): number;
get a1SheetName(): string;
get encodedA1SheetName(): string;
get lastColumnLetter(): string;
get cellStats(): {
nonEmpty: number;
loaded: number;
total: number;
};
getCellByA1(a1Address: A1Address): GoogleSpreadsheetCell;
getCell(rowIndex: RowIndex, columnIndex: ColumnIndex): GoogleSpreadsheetCell;
loadCells(sheetFilters?: DataFilterWithoutWorksheetId | DataFilterWithoutWorksheetId[]): Promise<void>;
saveUpdatedCells(): Promise<void>;
saveCells(cellsToUpdate: GoogleSpreadsheetCell[]): Promise<void>;
_ensureHeaderRowLoaded(): Promise<void>;
loadHeaderRow(headerRowIndex?: number): Promise<void>;
private _processHeaderRow;
setHeaderRow(headerValues: string[], headerRowIndex?: number): Promise<void>;
addRows(rows: RawRowData[], options?: AddRowOptions): Promise<GoogleSpreadsheetRow<Record<string, any>>[]>;
/**
* add a single row - see addRows for more info
*/
addRow(rowValues: RawRowData, options?: AddRowOptions): Promise<GoogleSpreadsheetRow<Record<string, any>>>;
private _rowCache;
getRows<T extends Record<string, any>>(options?: {
/** skip first N rows */offset?: number; /** limit number of rows fetched */
limit?: number;
}): Promise<GoogleSpreadsheetRow<T>[]>;
/**
* @internal
* Used internally to update row numbers after deleting rows.
* Should not be called directly.
* */
_shiftRowCache(deletedRowNumber: number): void;
/**
* @internal
* Used internally to update row numbers after deleting multiple rows.
* Should not be called directly.
* */
_shiftRowCacheBulk(startIndex: number, endIndex: number): void;
/**
* @internal
* Used internally to shift cell cache after deleting rows.
* Should not be called directly.
* */
_shiftCellCacheRows(startIndex: number, endIndex: number): void;
/**
* @internal
* Used internally to shift cell cache after deleting columns.
* Should not be called directly.
* */
_shiftCellCacheColumns(startIndex: number, endIndex: number): void;
clearRows(options?: {
start?: number;
end?: number;
}): Promise<void>;
/** @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UpdateSheetPropertiesRequest */
updateProperties(properties: Partial<Omit<WorksheetProperties, 'sheetId'>>): Promise<any>;
/**
* passes through the call to updateProperties to update only the gridProperties object
*/
updateGridProperties(gridProperties: Partial<WorksheetGridProperties>): Promise<any>;
/**
* resize, internally just calls updateGridProperties
*/
resize(gridProperties: Pick<WorksheetGridProperties, 'rowCount' | 'columnCount'>): Promise<any>;
/**
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#updatedimensionpropertiesrequest
*/
updateDimensionProperties(columnsOrRows: WorksheetDimension, properties: Partial<WorksheetDimensionProperties>, bounds: Partial<DimensionRangeIndexes>): Promise<any>;
getCellsInRange(a1Range: A1Range, options?: GetValuesRequestOptions): Promise<any>;
batchGetCellsInRange(a1Ranges: A1Range[], options?: GetValuesRequestOptions): Promise<any>;
/**
* Updates an existing named range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UpdateNamedRangeRequest
*/
updateNamedRange(/** ID of the named range to update */
namedRangeId: string, /** The named range properties to update */
namedRange: Partial<{
name: string;
range: GridRangeWithOptionalWorksheetId;
}>, /** Field mask specifying which properties to update */
fields: string): Promise<any>;
/**
* Creates a new named range in this worksheet (convenience method that auto-fills sheetId)
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddNamedRangeRequest
*/
addNamedRange(/** Name of the new named range */
name: string, /** GridRange describing the range (sheetId optional, will be auto-filled) */
range: GridRangeWithOptionalWorksheetId, /** Optional ID for the named range */
namedRangeId?: string): Promise<any>;
/**
* Deletes a named range (convenience wrapper)
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteNamedRangeRequest
*/
deleteNamedRange(/** ID of the named range to delete */
namedRangeId: string): Promise<any>;
/**
* Updates all cells in a range with the same cell data
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#RepeatCellRequest
*/
repeatCell(/** The range to update (sheetId optional) */
range: GridRangeWithOptionalWorksheetId, /** The cell data to repeat across the range */
cell: any, /** Which fields to update (use "*" for all fields) */
fields: string): Promise<void>;
/**
* Auto-fills cells with data following a pattern (like dragging the fill handle)
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AutoFillRequest
*/
autoFill(/** The range to autofill (detects source location automatically, sheetId optional) or explicit source and destination specification */
rangeOrSource: GridRangeWithOptionalWorksheetId | SourceAndDestination, /** Whether to generate data with the alternate series */
useAlternateSeries?: boolean): Promise<void>;
/**
* Cuts data from a source range and pastes it to a destination coordinate
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#CutPasteRequest
*/
cutPaste(/** The source range to cut from (sheetId optional) */
source: GridRangeWithOptionalWorksheetId, /** The top-left coordinate where data should be pasted (sheetId optional) */
destination: GridCoordinateWithOptionalWorksheetId, /** What kind of data to paste (defaults to PASTE_NORMAL) */
pasteType?: PasteType): Promise<void>;
/**
* Copies data from a source range and pastes it to a destination range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#CopyPasteRequest
*/
copyPaste(/** The source range to copy from (sheetId optional) */
source: GridRangeWithOptionalWorksheetId, /** The destination range to paste to (sheetId optional) */
destination: GridRangeWithOptionalWorksheetId, /** What kind of data to paste (defaults to PASTE_NORMAL) */
pasteType?: PasteType, /** How data should be oriented (defaults to NORMAL) */
pasteOrientation?: PasteOrientation): Promise<void>;
/**
* Merges all cells in the range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#MergeCellsRequest
*/
mergeCells(range: GridRangeWithOptionalWorksheetId, mergeType?: string): Promise<void>;
/**
* Unmerges cells in the given range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UnmergeCellsRequest
*/
unmergeCells(range: GridRangeWithOptionalWorksheetId): Promise<void>;
/**
* Updates borders for a range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UpdateBordersRequest
*/
updateBorders(/** The range whose borders should be updated (sheetId optional) */
range: GridRangeWithOptionalWorksheetId, /** Border styles for top, bottom, left, right, innerHorizontal, innerVertical */
borders: {
top?: any;
bottom?: any;
left?: any;
right?: any;
innerHorizontal?: any;
innerVertical?: any;
}): Promise<void>;
/**
* Adds a filter view to the sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddFilterViewRequest
*/
addFilterView(/** The filter view to add (filterViewId is optional and will be auto-generated if not provided) */
filter: FilterView): Promise<any>;
/**
* Appends cells after the last row with data in a sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AppendCellsRequest
*/
appendCells(/** The row data to append */
rows: any[], /** Which fields to update (use "*" for all fields) */
fields: string): Promise<void>;
/**
* Clears the basic filter on this sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#ClearBasicFilterRequest
*/
clearBasicFilter(): Promise<void>;
/**
* Delete rows or columns in a given range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteDimensionRequest
*/
deleteDimension(columnsOrRows: WorksheetDimension, rangeIndexes: DimensionRangeIndexes): Promise<any>;
/**
* Delete rows by index
*/
deleteRows(/** the start row index (inclusive, 0-based) */
startIndex: number, /** the end row index (exclusive) */
endIndex: number): Promise<any>;
/**
* Delete columns by index
*/
deleteColumns(/** the start column index (inclusive, 0-based) */
startIndex: number, /** the end column index (exclusive) */
endIndex: number): Promise<any>;
deleteEmbeddedObject(): Promise<void>;
/**
* Deletes a filter view from the sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteFilterViewRequest
*/
deleteFilterView(/** The ID of the filter view to delete */
filterId: Integer): Promise<void>;
/**
* Duplicates a filter view
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DuplicateFilterViewRequest
*/
duplicateFilterView(/** The ID of the filter view to duplicate */
filterId: Integer): Promise<void>;
/**
* Duplicate worksheet within the document
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DuplicateSheetRequest
*/
duplicate(options?: {
id?: WorksheetId;
title?: string;
index?: number;
}): Promise<GoogleSpreadsheetWorksheet>;
/**
* Finds and replaces text in cells
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#FindReplaceRequest
*/
findReplace(/** The value to search for */
find: string, /** The value to use as replacement */
replacement: string, /** Search options (matchCase, matchEntireCell, searchByRegex, includeFormulas) */
options?: {
matchCase?: boolean;
matchEntireCell?: boolean;
searchByRegex?: boolean;
includeFormulas?: boolean;
}, /** Optional range to search in (defaults to entire sheet, sheetId optional) */
range?: GridRangeWithOptionalWorksheetId): Promise<void>;
/**
* Inserts rows or columns at a particular index
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#InsertDimensionRequest
*/
insertDimension(columnsOrRows: WorksheetDimension, rangeIndexes: DimensionRangeIndexes, inheritFromBefore?: boolean): Promise<any>;
/**
* insert empty cells in a range, shifting existing cells in the specified direction
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#InsertRangeRequest
*/
insertRange(/** the range to insert new cells into */
range: GridRangeWithOptionalWorksheetId, /** which direction to shift existing cells - ROWS (shift down) or COLUMNS (shift right) */
shiftDimension: WorksheetDimension): Promise<void>;
/**
* Moves rows or columns to a different position within the sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#MoveDimensionRequest
*/
moveDimension(/** Whether to move rows or columns */
dimension: WorksheetDimension, /** The indexes of rows/columns to move */
source: DimensionRangeIndexes, /** Where to move them (calculated before removal) */
destinationIndex: number): Promise<void>;
updateEmbeddedObjectPosition(): Promise<void>;
/**
* Inserts data into the spreadsheet starting at the specified coordinate
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#PasteDataRequest
*/
pasteData(/** The coordinate at which the data should start being inserted (sheetId optional) */
coordinate: GridCoordinateWithOptionalWorksheetId, /** The data to insert */
data: string, /** The delimiter in the data */
delimiter: string, /** How the data should be pasted (defaults to PASTE_NORMAL) */
type?: PasteType): Promise<void>;
/**
* Splits a column of text into multiple columns based on a delimiter
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#TextToColumnsRequest
*/
textToColumns(/** The column to split (must span exactly one column) */
source: GridRangeWithOptionalWorksheetId, /** Type of delimiter to use */
delimiterType: DelimiterType, /** Custom delimiter character (only used when delimiterType is CUSTOM) */
delimiter?: string): Promise<void>;
/**
* Updates properties of a filter view
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UpdateFilterViewRequest
*/
updateFilterView(/** The new properties of the filter view */
filter: FilterView, /** The fields that should be updated (use "*" to update all fields) */
fields: string): Promise<void>;
/**
* Deletes a range of cells and shifts remaining cells
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteRangeRequest
*/
deleteRange(/** The range of cells to delete (sheetId optional) */
range: GridRangeWithOptionalWorksheetId, /** How remaining cells should shift (ROWS = up, COLUMNS = left) */
shiftDimension: WorksheetDimension): Promise<void>;
/**
* Appends rows or columns to the end of a sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AppendDimensionRequest
*/
appendDimension(/** Whether rows or columns should be appended */
dimension: WorksheetDimension, /** The number of rows or columns to append */
length: number): Promise<void>;
/**
* Adds a new conditional formatting rule at the given index
* All subsequent rules' indexes are incremented
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddConditionalFormatRuleRequest
*/
addConditionalFormatRule(/** The rule to add */
rule: ConditionalFormatRule, /** The zero-based index where the rule should be inserted */
index: Integer): Promise<void>;
/**
* Updates a conditional format rule at the given index, or moves a conditional format rule to another index
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UpdateConditionalFormatRuleRequest
*/
updateConditionalFormatRule(/** Either provide `rule` to replace the rule, or `newIndex` and `sheetId` to move it */
options: {
/** The zero-based index of the rule */index: Integer; /** The rule that should replace the rule at the given index (mutually exclusive with newIndex) */
rule?: ConditionalFormatRule; /** The zero-based new index the rule should end up at (mutually exclusive with rule, requires sheetId) */
newIndex?: Integer; /** The sheet of the rule to move (required if newIndex is set) */
sheetId?: WorksheetId;
}): Promise<void>;
/**
* Deletes a conditional format rule at the given index
* All subsequent rules' indexes are decremented
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteConditionalFormatRuleRequest
*/
deleteConditionalFormatRule(/** The zero-based index of the rule to be deleted */
index: Integer, /** The sheet the rule is being deleted from (defaults to this sheet) */
sheetId?: WorksheetId): Promise<void>;
/**
* Sorts data in rows based on sort order per column
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#SortRangeRequest
*/
sortRange(/** The range to sort (sheetId optional) */
range: GridRangeWithOptionalWorksheetId, /** Array of sort specifications (later specs used when values are equal) */
sortSpecs: SortSpec[]): Promise<void>;
/**
* Sets (or unsets) a data validation rule to every cell in the range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#SetDataValidationRequest
*/
setDataValidation(range: GridRangeWithOptionalWorksheetId, /** data validation rule object, or set to false to clear an existing rule */
rule: DataValidationRule | false): Promise<any>;
/**
* Sets the basic filter on this sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#SetBasicFilterRequest
*/
setBasicFilter(/** The basic filter configuration (range will auto-fill sheetId if not provided) */
filter: {
range?: GridRangeWithOptionalWorksheetId;
sortSpecs?: SortSpec[];
filterSpecs?: any[];
}): Promise<void>;
/**
* add a new protected range to the sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddProtectedRangeRequest
*/
addProtectedRange(protectedRange: ProtectedRange): Promise<any>;
/**
* update an existing protected range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UpdateProtectedRangeRequest
*/
updateProtectedRange(protectedRangeId: Integer, protectedRange: Partial<ProtectedRange>): Promise<any>;
/**
* delete a protected range by ID
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteProtectedRangeRequest
*/
deleteProtectedRange(protectedRangeId: Integer): Promise<any>;
/**
* auto-resize rows or columns to fit their contents
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AutoResizeDimensionsRequest
*/
autoResizeDimensions(/** which dimension to auto-resize */
columnsOrRows: WorksheetDimension, /** start and end indexes (optional, defaults to all) */
rangeIndexes?: DimensionRangeIndexes): Promise<any>;
addChart(): Promise<void>;
updateChartSpec(): Promise<void>;
/**
* Updates properties of a banded range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UpdateBandingRequest
*/
updateBanding(/** The banded range to update with the new properties */
bandedRange: BandedRange, /** The fields that should be updated (use "*" to update all fields) */
fields: string): Promise<void>;
/**
* Adds a new banded range to the sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddBandingRequest
*/
addBanding(/** The banded range to add (bandedRangeId is optional and will be auto-generated if not provided) */
bandedRange: BandedRange): Promise<any>;
/**
* Deletes a banded range from the sheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteBandingRequest
*/
deleteBanding(/** The ID of the banded range to delete */
bandedRangeId: Integer): Promise<void>;
/**
* Creates developer metadata
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#CreateDeveloperMetadataRequest
*/
createDeveloperMetadata(/** The developer metadata to create */
developerMetadata: DeveloperMetadata): Promise<any>;
/**
* Updates developer metadata that matches the specified filters
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#UpdateDeveloperMetadataRequest
*/
updateDeveloperMetadata(/** The filters matching the developer metadata entries to update */
dataFilters: DataFilterObject[], /** The value that all metadata matched by the filters will be updated to */
developerMetadata: DeveloperMetadata, /** The fields that should be updated (use "*" to update all fields) */
fields: string): Promise<void>;
/**
* Deletes developer metadata that matches the specified filter
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteDeveloperMetadataRequest
*/
deleteDeveloperMetadata(/** The filter describing the criteria used to select which developer metadata to delete */
dataFilter: DataFilterObject): Promise<void>;
/**
* Randomizes the order of rows in a range
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#RandomizeRangeRequest
*/
randomizeRange(/** The range to randomize (sheetId optional) */
range: GridRangeWithOptionalWorksheetId): Promise<void>;
addDimensionGroup(): Promise<void>;
deleteDimensionGroup(): Promise<void>;
updateDimensionGroup(): Promise<void>;
/**
* Trims whitespace from the start and end of each cell's text
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#TrimWhitespaceRequest
*/
trimWhitespace(/** The range whose cells to trim (sheetId optional) */
range: GridRangeWithOptionalWorksheetId): Promise<void>;
/**
* Removes duplicate rows from a range based on specified columns
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteDuplicatesRequest
*/
deleteDuplicates(/** The range to remove duplicates from (sheetId optional) */
range: GridRangeWithOptionalWorksheetId, /** Columns to check for duplicates (if empty, all columns are used) */
comparisonColumns?: DimensionRange[]): Promise<void>;
addSlicer(): Promise<void>;
updateSlicerSpec(): Promise<void>;
/**
* delete this worksheet
*/
delete(): Promise<void>;
/**
* copies this worksheet into another document/spreadsheet
*
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo
*/
copyToSpreadsheet(destinationSpreadsheetId: SpreadsheetId): Promise<any>;
/**
* clear data in the sheet - either the entire sheet or a specific range
*/
clear(/** optional A1 range to clear - defaults to entire sheet */
a1Range?: A1Range): Promise<void>;
/**
* exports worksheet as CSV file (comma-separated values)
*/
downloadAsCSV(): Promise<ArrayBuffer>;
downloadAsCSV(returnStreamInsteadOfBuffer: false): Promise<ArrayBuffer>;
downloadAsCSV(returnStreamInsteadOfBuffer: true): Promise<ReadableStream$1>;
/**
* exports worksheet as TSC file (tab-separated values)
*/
downloadAsTSV(): Promise<ArrayBuffer>;
downloadAsTSV(returnStreamInsteadOfBuffer: false): Promise<ArrayBuffer>;
downloadAsTSV(returnStreamInsteadOfBuffer: true): Promise<ReadableStream$1>;
/**
* exports worksheet as PDF
*/
downloadAsPDF(): Promise<ArrayBuffer>;
downloadAsPDF(returnStreamInsteadOfBuffer: false): Promise<ArrayBuffer>;
downloadAsPDF(returnStreamInsteadOfBuffer: true): Promise<ReadableStream$1>;
}
//#endregion
//#region src/lib/types/drive-types.d.ts
type PermissionRoles = 'owner' | 'writer' | 'commenter' | 'reader';
type PublicPermissionRoles = Exclude<PermissionRoles, 'owner'>;
type PublicPermissionListEntry = {
id: 'anyoneWithLink';
type: 'anyone';
role: PublicPermissionRoles;
};
type UserOrGroupPermissionListEntry = {
id: string;
displayName: string;
type: 'user' | 'group';
photoLink?: string;
emailAddress: string;
role: PermissionRoles;
deleted: boolean;
};
type DomainPermissionListEntry = {
id: string;
displayName: string;
type: 'domain';
domain: string;
role: PublicPermissionRoles;
photoLink?: string;
};
type PermissionsList = (PublicPermissionListEntry | UserOrGroupPermissionListEntry | DomainPermissionListEntry)[];
//#endregion
//#region src/lib/types/auth-types.d.ts
/** single type to handle all valid auth types */
type GoogleApiAuth = {
getRequestHeaders: () => Promise<any>;
} | {
apiKey: string;
} | {
token: string;
};
declare enum AUTH_MODES {
GOOGLE_AUTH_CLIENT = "google_auth",
RAW_ACCESS_TOKEN = "raw_access_token",
API_KEY = "api_key"
}
//#endregion
//#region src/lib/GoogleSpreadsheet.d.ts
declare const EXPORT_CONFIG: Record<string, {
singleWorksheet?: boolean;
}>;
type ExportFileTypes = keyof typeof EXPORT_CONFIG;
/**
* Google Sheets document
*
* @description
* **This class represents an entire google spreadsheet document**
* Provides methods to interact with document metadata/settings, formatting, manage sheets, and acts as the main gateway to interacting with sheets and data that the document contains.q
*
*/
declare class GoogleSpreadsheet {
readonly spreadsheetId: string;
auth: GoogleApiAuth;
get authMode(): AUTH_MODES;
private _rawSheets;
private _rawProperties;
private _spreadsheetUrl;
private _deleted;
/**
* Sheets API [ky](https://github.com/sindresorhus/ky?tab=readme-ov-file#kycreatedefaultoptions) instance
* authentication is automatically attached
* can be used if unsupported sheets calls need to be made
* @see https://developers.google.com/sheets/api/reference/rest
* */
readonly sheetsApi: KyInstance;
/**
* Drive API [ky](https://github.com/sindresorhus/ky?tab=readme-ov-file#kycreatedefaultoptions) instance
* authentication automatically attached
* can be used if unsupported drive calls need to be made
* @topic permissions
* @see https://developers.google.com/drive/api/v3/reference
* */
readonly driveApi: KyInstance;
/**
* initialize new GoogleSpreadsheet
* @category Initialization
* */
constructor(/** id of Google spreadsheet doc */
spreadsheetId: SpreadsheetId, /** authentication to use with Google Sheets API */
auth: GoogleApiAuth, /** Additional options */
options?: {
/**
* customize retry behavior --
* see the [ky documentation](https://github.com/sindresorhus/ky#retry) for details of the available options and defaults.
* */
retryConfig?: RetryOptions | number;
});
/** @internal */
_setAuthRequestHook(req: Request): Promise<Request>;
/** @internal */
_errorHook(error: Error): Promise<Error>;
/** @internal */
_makeSingleUpdateRequest(requestType: string, requestParams: any): Promise<any>;
/** @internal */
_makeBatchUpdateRequest(requests: any[], responseRanges?: string | string[]): Promise<void>;
/** @internal */
_ensureInfoLoaded(): void;
/** @internal */
_updateRawProperties(newProperties: SpreadsheetProperties): void;
/** @internal */
_updateOrCreateSheet(sheetInfo: {
properties: WorksheetProperties;
data: any;
protectedRanges?: ProtectedRange[];
}): void;
_getProp(param: keyof SpreadsheetProperties): any;
get title(): SpreadsheetProperties['title'];
get locale(): SpreadsheetProperties['locale'];
get timeZone(): SpreadsheetProperties['timeZone'];
get autoRecalc(): SpreadsheetProperties['autoRecalc'];
get defaultFormat(): SpreadsheetProperties['defaultFormat'];
get spreadsheetTheme(): SpreadsheetProperties['spreadsheetTheme'];
get iterativeCalculationSettings(): SpreadsheetProperties['iterativeCalculationSettings'];
/**
* update spreadsheet properties
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#SpreadsheetProperties
* */
updateProperties(properties: Partial<SpreadsheetProperties>): Promise<void>;
loadInfo(includeCells?: boolean): Promise<void>;
resetLocalCache(): void;
get sheetCount(): number;
get sheetsById(): Record<WorksheetId, GoogleSpreadsheetWorksheet>;
get sheetsByIndex(): GoogleSpreadsheetWorksheet[];
get sheetsByTitle(): Record<string, GoogleSpreadsheetWorksheet>;
/**
* Add new worksheet to document
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddSheetRequest
* */
addSheet(properties?: Partial<RecursivePartial<WorksheetProperties> & {
headerValues: string[];
headerRowIndex: number;
}>): Promise<GoogleSpreadsheetWorksheet>;
/**
* delete a worksheet
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteSheetRequest
* */
deleteSheet(sheetId: WorksheetId): Promise<void>;
/**
* create a new named range
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddNamedRangeRequest
*/
addNamedRange(/** name of new named range */
name: string, /** GridRange object describing range */
range: GridRange, /** id for named range (optional) */
namedRangeId?: string): Promise<any>;
/**
* delete a named range
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteNamedRangeRequest
* */
deleteNamedRange(/** id of named range to delete */
namedRangeId: NamedRangeId): Promise<any>;
/** fetch cell data into local cache */
loadCells(
/**
* single filter or array of filters
* strings are treated as A1 ranges, objects are treated as GridRange objects,
* objects with a `developerMetadataLookup` key are treated as DeveloperMetadataLookup filters
* pass nothing to fetch all cells
* */
filters?: DataFilter | DataFilter[]): Promise<void>;
/**
* export/download helper, not meant to be called directly (use downloadAsX methods on spreadsheet and worksheet instead)
* @internal
*/
_downloadAs(fileType: ExportFileTypes, worksheetId: WorksheetId | undefined, returnStreamInsteadOfBuffer?: boolean): Promise<ArrayBuffer | node_stream_web0.ReadableStream<any> | null>;
/**
* exports entire document as html file (zipped)
* @topic export
* */
downloadAsZippedHTML(): Promise<ArrayBuffer>;
downloadAsZippedHTML(returnStreamInsteadOfBuffer: false): Promise<ArrayBuffer>;
downloadAsZippedHTML(returnStreamInsteadOfBuffer: true): Promise<ReadableStream>;
/**
* @deprecated
* use `doc.downloadAsZippedHTML()` instead
* */
downloadAsHTML(returnStreamInsteadOfBuffer?: boolean): Promise<ArrayBuffer | node_stream_web0.ReadableStream<any> | null>;
/**
* exports entire document as xlsx spreadsheet (Microsoft Office Excel)
* @topic export
* */
downloadAsXLSX(): Promise<ArrayBuffer>;
downloadAsXLSX(returnStreamInsteadOfBuffer: false): Promise<ArrayBuffer>;
downloadAsXLSX(returnStreamInsteadOfBuffer: true): Promise<ReadableStream>;
/**
* exports entire document as ods spreadsheet (Open Office)
* @topic export
*/
downloadAsODS(): Promise<ArrayBuffer>;
downloadAsODS(returnStreamInsteadOfBuffer: false): Promise<ArrayBuffer>;
downloadAsODS(returnStreamInsteadOfBuffer: true): Promise<ReadableStream>;
delete(): Promise<void>;
/**
* list all permissions entries for doc
*/
listPermissions(): Promise<PermissionsList>;
setPublicAccessLevel(role: PublicPermissionRoles | false): Promise<void>;
/** share document to email or domain */
share(emailAddressOrDomain: string, opts?: {
/** set role level, defaults to owner */role?: PermissionRoles; /** set to true if email is for a group */
isGroup?: boolean; /** set to string to include a custom message, set to false to skip sending a notification altogether */
emailMessage?: string | false;
}): Promise<unknown>;
/**
* delete a permission by its ID
* @see https://developers.google.com/drive/api/v3/reference/permissions/delete
*/
deletePermission(permissionId: string): Promise<void>;
/**
* search for developer metadata entries matching the given filters
* @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata/search
*/
searchDeveloperMetadata(/** array of DataFilter objects to match against */
filters: DataFilterObject[]): Promise<DeveloperMetadata[]>;
static createNewSpreadsheetDocument(auth: GoogleApiAuth, properties?: Partial<SpreadsheetProperties>): Promise<GoogleSpreadsheet>;
}
//#endregion
export { GoogleSpreadsheet, GoogleSpreadsheetCell, GoogleSpreadsheetCellErrorValue, GoogleSpreadsheetRow, GoogleSpreadsheetWorksheet };
//# sourceMappingURL=index.d.cts.map