### Initialize Google Spreadsheets with Service Account JWT Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/migration-guide.md Use the google-auth-library directly for authentication. This example shows how to initialize the JWT client with service account credentials. ```javascript import { JWT } from 'google-auth-library'; import creds from './service-account-creds-file.json'; const serviceAccountJWT = new JWT({ email: creds.client_email, key: creds.private_key, scopes: [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive.file', ], }); const doc = new GoogleSpreadsheet('YOUR-DOC-ID', serviceAccountJWT); ``` -------------------------------- ### Handle Line Breaks in Private Key for Heroku Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/authentication.md This example demonstrates how to correctly handle private keys with line breaks when using platforms like Heroku, where environment variables might be encoded. ```javascript const jwtFromEnv = new JWT({ email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL, key: process.env.GOOGLE_PRIVATE_KEY.replace(/\n/g, "\n"), scopes: SCOPES, }); ``` -------------------------------- ### Export Worksheet as CSV (Stream) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/exports.md This example demonstrates downloading a worksheet as a CSV file using stream mode. Set the second argument to `true` to enable stream mode, allowing for incremental data processing. The code converts a Web ReadableStream to a Node.js stream for piping to a file. ```javascript import { Readable } from 'node:stream'; // ... const doc = new GoogleSpreadsheet('', auth); const csvStream = await doc.downloadAsCSV(true); // this `true` arg toggles to stream mode const writableStream = fs.createWriteStream('./my-export-stream.csv'); writableStream.on('finish', () => { console.log('done'); }); writableStream.on('error', (err) => { console.log(err); }); // convert the ReadableStream (web response) to a normal Node.js stream // and pipe to the fs writable stream Readable.fromWeb(csvStream).pipe(writableStream); ``` -------------------------------- ### Delete Columns by Index Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md A convenience method to delete a range of columns by their start and end indices. It is a wrapper around `deleteDimension`. ```javascript await sheet.deleteColumns(5, 10); ``` -------------------------------- ### pasteData Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Inserts data into the spreadsheet starting at the specified coordinate. This method does not update cached rows/cells, so a reload is necessary before accessing the newly pasted data. ```APIDOC ## pasteData(coordinate, data, delimiter, type) ### Description Inserts data into the spreadsheet starting at the specified coordinate. ### Method (async) ### Parameters #### Path Parameters - **coordinate** (Object
[GridCoordinate]) - Required - The coordinate at which the data should start being inserted, sheetId not required - **coordinate.rowIndex** (Number
_int >= 0_) - Required - The row index (0-based) - **coordinate.columnIndex** (Number
_int >= 0_) - Required - The column index (0-based) - **data** (String) - Required - The data to insert - **delimiter** (String) - Required - The delimiter in the data (e.g., ',' for CSV, '\t' for TSV) #### Query Parameters - **type** (String (enum)
[PasteType]) - Optional - How the data should be pasted. _defaults to `PASTE_NORMAL`_ ### Side effects data is inserted into the sheet at the specified coordinate ### Warning Does not update cached rows/cells, so be sure to reload rows/cells before trying to access the newly pasted data ``` -------------------------------- ### Preview Documentation Locally Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/README.md Run this command to preview the docs site locally and make edits. Navigate to http://localhost:3000 afterwards. ```bash npm run docs:preview ``` -------------------------------- ### Basic Google Spreadsheet Initialization and Properties Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/README.md Demonstrates initializing a GoogleSpreadsheet instance with JWT authentication, loading document information, and updating document properties. It also shows how to access and interact with worksheets. ```javascript import { GoogleSpreadsheet } from 'google-spreadsheet'; import { JWT } from 'google-auth-library'; // Initialize auth - see https://theoephraim.github.io/node-google-spreadsheet/#/guides/authentication const serviceAccountAuth = new JWT({ // env var values here are copied from service account credentials generated by google // see "Authentication" section in docs for more info email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL, key: process.env.GOOGLE_PRIVATE_KEY, scopes: ['https://www.googleapis.com/auth/spreadsheets'], }); const doc = new GoogleSpreadsheet('', serviceAccountAuth); await doc.loadInfo(); // loads document properties and worksheets console.log(doc.title); await doc.updateProperties({ title: 'renamed doc' }); const sheet = doc.sheetsByIndex[0]; // or use `doc.sheetsById[id]` or `doc.sheetsByTitle[title]` console.log(sheet.title); console.log(sheet.rowCount); // adding / removing sheets const newSheet = await doc.addSheet({ title: 'another sheet' }); await newSheet.delete(); ``` -------------------------------- ### Delete Rows by Index Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md A convenience method to delete a range of rows by their start and end indices. It is a wrapper around `deleteDimension`. ```javascript await sheet.deleteRows(5, 10); ``` -------------------------------- ### clearRows Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Clears rows in the sheet. By default, this clears all rows and leaves the header intact, but a start and end row can be specified. ```APIDOC ## clearRows(options) ### Description Clear rows in the sheet. ### Parameters #### Path Parameters - **options** (Object) - Optional - Options object. - **options.start** (Number) - Optional - A1 style row number of first row to clear. Defaults to the first non-header row. - **options.end** (Number) - Optional - A1 style row number of last row to clear. Defaults to the last row. ### Side Effects - rows in the sheet are emptied - loaded GoogleSpreadsheetRows in the cache have the data cleared ``` -------------------------------- ### Initialize OAuth2Client and Authenticate Google Spreadsheet Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/authentication.md Demonstrates how to initialize an OAuth2Client with application credentials and user tokens, then use it to authenticate a GoogleSpreadsheet instance. It also shows how to listen for new access token events. ```javascript const { OAuth2Client } = require('google-auth-library'); // Initialize the OAuth2Client with your app's oauth credentials const oauthClient = new OAuth2Client({ clientId: process.env.GOOGLE_OAUTH_CLIENT_ID, clientSecret: process.env.GOOGLE_OAUTH_CLIENT_SECRET, }); // Pre-configure the client with credentials you have stored in e.g. your database // NOTE - `refresh_token` is required, `access_token` and `expiry_date` are optional // (the refresh token is used to generate a missing/expired access token) const { accessToken, refreshToken, expiryDate } = await fetchUserGoogleCredsFromDatabase(); oauthClient.credentials.access_token = accessToken; oauthClient.credentials.refresh_token = refreshToken; oauthClient.credentials.expiry_date = expiryDate; // Unix epoch milliseconds // Listen in whenever a new access token is obtained, as you might want to store the new token in your database // Note that the refresh_token never changes (unless it's revoked, in which case your end-user will // need to go through the full authentication flow again), so storing the new access_token is optional oauthClient.on('tokens', (credentials) => { console.log(credentials.access_token); console.log(credentials.scope); console.log(credentials.expiry_date); console.log(credentials.token_type); // will always be 'Bearer' }) const doc = new GoogleSpreadsheet('', oauthClient); ``` -------------------------------- ### Authenticate with Service Account Credentials Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/authentication.md Use this method when you have your service account's JSON key file locally. Ensure the file path is correct and the `client_email` and `private_key` are accessible. ```javascript import { JWT } from 'google-auth-library' import creds from './config/myapp-1dd646d7c2af.json'; // the file saved above const SCOPES = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive.file', ]; const jwt = new JWT({ email: creds.client_email, key: creds.private_key, scopes: SCOPES, }); const doc = new GoogleSpreadsheet('', jwt); ``` -------------------------------- ### downloadAsHTML(returnStreamInsteadOfBuffer) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Exports the entire document in HTML format as a zip file. Optionally, you can return a stream instead of a buffer. ```APIDOC ## downloadAsHTML(returnStreamInsteadOfBuffer) ### Description Export entire document in HTML format (zip file). ### Method async ### Parameters #### Query Parameters - **returnStreamInsteadOfBuffer** (Boolean) - Optional - Set to true to return a stream instead of a Buffer. See [Exports guide](guides/exports) for more details. ### Returns - Buffer (or stream) containing HTML data (in a zip file) ``` -------------------------------- ### Authenticate with Service Account from Environment Variables Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/authentication.md This approach is preferred for security, loading service account credentials from environment variables. Ensure `GOOGLE_SERVICE_ACCOUNT_EMAIL` and `GOOGLE_PRIVATE_KEY` are set. ```javascript const jwtFromEnv = new JWT({ email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL, key: process.env.GOOGLE_PRIVATE_KEY, scopes: SCOPES, }); ``` -------------------------------- ### Create and Initialize a New Google Spreadsheet Document Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Create a new Google Spreadsheet document with a specified title and load its initial information. The document is owned by the authenticated user, which might be a service account. ```javascript const doc = await GoogleSpreadsheet.createNewSpreadsheetDocument(jwt, { title: 'This is a new doc' }); console.log(doc.spreadsheetId); const sheet1 = doc.sheetsByIndex[0]; ``` -------------------------------- ### Loading and Interacting with Rows Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-row.md Demonstrates how to load rows from a sheet, access row data using header keys, update values, save changes, and add new rows. ```javascript const doc = new GoogleSpreadsheet('', auth); await doc.loadInfo(); // loads sheets const sheet = doc.sheetsByIndex[0]; // the first sheet const rows = await sheet.getRows(); console.log(rows.length); // 2 console.log(rows[0].get('name')); // 'Larry Page' console.log(rows[0].get('email')); // 'larry@google.com' // make updates rows[1].set('email', 'sergey@abc.xyz'); await rows[1].save(); // save changes // add new row, returns a GoogleSpreadsheetRow object const sundar = await sheet.addRow({ name: 'Sundar Pichai', email: 'sundar@abc.xyz' }); ``` -------------------------------- ### Loading, Accessing, and Updating Cells Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/README.md Demonstrates how to load a range of cells into a local cache, access individual cells by index or A1 notation, and update their values, formulas, formatting, and notes. All updates are saved in a single call. ```javascript await sheet.loadCells('A1:E10'); // loads range of cells into local cache - DOES NOT RETURN THE CELLS console.log(sheet.cellStats); // total cells, loaded, how many non-empty const a1 = sheet.getCell(0, 0); // access cells using a zero-based index const c6 = sheet.getCellByA1('C6'); // or A1 style notation // access everything about the cell console.log(a1.value); console.log(a1.formula); console.log(a1.formattedValue); // update the cell contents and formatting a1.value = 123.456; c6.formula = '=A1'; a1.textFormat = { bold: true }; c6.note = 'This is a note!'; await sheet.saveUpdatedCells(); // save all updates in one call ``` -------------------------------- ### Working with Rows in a Spreadsheet Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/README.md Shows how to add rows with headers, append multiple rows, read rows, and update or delete individual rows. ```javascript // if creating a new sheet, you can set the header row const sheet = await doc.addSheet({ headerValues: ['name', 'email'] }); // append rows const larryRow = await sheet.addRow({ name: 'Larry Page', email: 'larry@google.com' }); const moreRows = await sheet.addRows([ { name: 'Sergey Brin', email: 'sergey@google.com' }, { name: 'Eric Schmidt', email: 'eric@google.com' }, ]); // read rows const rows = await sheet.getRows(); // can pass in { limit, offset } // read/write row values console.log(rows[0].get('name')); // 'Larry Page' rows[1].set('email', 'sergey@abc.xyz'); // update a value rows[2].assign({ name: 'Sundar Pichai', email: 'sundar@google.com' }); // set multiple values await rows[2].save(); // save updates on a row await rows[2].delete(); // delete a row ``` -------------------------------- ### Initialize Application Default Credentials (ADC) for Google Spreadsheet Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/authentication.md Shows how to initialize GoogleAuth with specified scopes for Application Default Credentials, and then use this to authenticate a GoogleSpreadsheet instance. This method is suitable for authenticating within Google infrastructure. ```javascript const { GoogleAuth } = require('google-auth-library'); const adcAuth = new GoogleAuth({ scopes: ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive.file'], }); const doc = new GoogleSpreadsheet('', adcAuth); ``` -------------------------------- ### downloadAsODS(returnStreamInsteadOfBuffer) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Exports the entire document in ODS (Open Document Format). The output can be returned as a buffer or a stream. ```APIDOC ## downloadAsODS(returnStreamInsteadOfBuffer) ### Description Export entire document in ODS (Open Document Format) format. ### Method async ### Parameters #### Query Parameters - **returnStreamInsteadOfBuffer** (Boolean) - Optional - Set to true to return a stream instead of a Buffer. See [Exports guide](guides/exports) for more details. ### Returns - Buffer (or stream) containing ODS data ``` -------------------------------- ### Authenticate with Raw Token Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/authentication.md Provide a pre-managed authentication token directly to the library. This is useful if you are handling token management outside of the standard google-auth-library. ```javascript const doc = new GoogleSpreadsheet('', { token: someTokenYouAreManaging }); ``` -------------------------------- ### downloadAsXLSX(returnStreamInsteadOfBuffer) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Exports the entire document in XLSX (Excel) format. You can choose to receive the output as a buffer or a stream. ```APIDOC ## downloadAsXLSX(returnStreamInsteadOfBuffer) ### Description Export entire document in XLSX (excel) format. ### Method async ### Parameters #### Query Parameters - **returnStreamInsteadOfBuffer** (Boolean) - Optional - Set to true to return a stream instead of a Buffer. See [Exports guide](guides/exports) for more details. ### Returns - Buffer (or stream) containing XLSX data ``` -------------------------------- ### Reading and Updating Row Values Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-row.md Demonstrates how to retrieve row data using header keys and update values before saving. ```APIDOC ## get(key) ### Description Get value of specific cell using header key ### Parameters #### Path Parameters - **key** (String) - Description: header value ## set(key, value) ### Description Set value of specific cell using header key ### Parameters #### Path Parameters - **key** (String) - Description: header value - **value** (String) - Description: new value ## assign(valuesObject) ### Description Assign multiple values in the row at once Similar to `Object.assign()` ### Parameters #### Path Parameters - **valuesObject** (Object) - Description: key-value object of data to set ``` -------------------------------- ### Typed Row Data with TypeScript Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/migration-guide.md Demonstrates how to specify the shape of row data using TypeScript for type checking and improved developer experience. ```typescript type UserRow = { first_name: string; email: string }; const userRows = await sheet.getRows(); const name = userRows[0].get('first_name'); // key checked to exist, value is typed // type errors userRows[0].get('bad_key'); // key does not exist! userRows[0].set('first_name', 123); // type of value is wrong ``` -------------------------------- ### GoogleSpreadsheet Initialization Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Initializes a GoogleSpreadsheet instance to work with an existing document using its ID and authentication details. It also supports custom retry configurations for HTTP requests. ```APIDOC ## `new GoogleSpreadsheet(spreadsheetId, auth, options)` ### Description Work with an existing Google Spreadsheet document using its unique ID and authentication credentials. ### Parameters #### Path Parameters - **spreadsheetId** (String) - Required - The unique identifier of the Google Spreadsheet document. - **auth** (GoogleAuth | JWT | OAuth2Client | { apiKey: string } | { token: string }) - Required - The authentication object or credentials to use for accessing the document. See [Authentication](guides/authentication) for more info. - **options** ( { retryConfig: RetryConfig | number } ) - Optional - Options for configuring library behavior, including automatic request retries. Defaults to 2 retries (3 total attempts) for network errors and specific HTTP status codes. Can be set to a number to specify the retry limit or an object for detailed configuration. ### Request Example ```javascript // Example with default retry settings const doc = new GoogleSpreadsheet('YOUR_SPREADSHEET_ID', yourAuthObject); // Example with custom retry settings const doc = new GoogleSpreadsheet('YOUR_SPREADSHEET_ID', yourAuthObject, { retryConfig: { limit: 5, backoffLimit: 3000 } }); ``` ### Response - **GoogleSpreadsheet** - An instance of the GoogleSpreadsheet class, with the document ID and info loaded. ``` -------------------------------- ### Setting a Formula in a Row Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-row.md Shows how to set a formula in a row property. The formula will be resolved to its value after the row is saved. ```javascript const row = await doc.addRow({ col1: '=A1' }); console.log(row.get('col1')); // logs '=A1', the formula has not been actually resolved yet await row.save(); // cell will now contain the value from cell A1 ``` -------------------------------- ### Manage Google Spreadsheet Docs Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/README.md Use this snippet to authenticate, create a new spreadsheet document, share it with specific users or domains, set public access levels, and delete the document. Ensure you have the necessary Google Cloud credentials and scopes configured. ```javascript const auth = new JWT({ email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL, key: process.env.GOOGLE_PRIVATE_KEY, scopes: [ 'https://www.googleapis.com/auth/spreadsheets', // note that sharing-related calls require the google drive scope 'https://www.googleapis.com/auth/drive.file', ], }); // create a new doc const newDoc = await GoogleSpreadsheet.createNewSpreadsheetDocument(auth, { title: 'new fancy doc' }); // share with specific users, domains, or make public await newDoc.share('someone.else@example.com'); await newDoc.share('mycorp.com'); await newDoc.setPublicAccessLevel('reader'); // delete doc await newDoc.delete(); ``` -------------------------------- ### listPermissions() Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Lists all permission entries for a Google Sheet. Requires Drive API scopes. ```APIDOC ## listPermissions() ### Description Lists all permission entries for a Google Sheet. ### Method `async` ### Returns `Promise` ### Example ```js const permissions = await doc.listPermissions(); ``` ``` -------------------------------- ### Export Document as XLSX (ArrayBuffer) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/exports.md Use this method to download the entire Google Spreadsheet document as an XLSX file. The data is returned as an ArrayBuffer, which can then be written to a file. ```javascript const doc = new GoogleSpreadsheet('', auth); const xlsxBuffer = await doc.downloadAsXLSX(); await fs.writeFile('./my-export.xlsx', Buffer.from(xlsxBuffer)); ``` -------------------------------- ### Top-Level Await Wrapper Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/README.md A common pattern to enable top-level await in environments that do not support it directly. Wrap your async code within an immediately invoked async function expression. ```javascript (async function () { await someAsyncFunction(); })(); ``` -------------------------------- ### Typed Row Operations with TypeScript Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/README.md Demonstrates how to use TypeScript generics with `getRows` to provide type safety when accessing row data. ```typescript type UsersRowData = { name: string; email: string; type?: 'admin' | 'user'; }; const userRows = await sheet.getRows(); userRows[0].get('name'); // <- TS is happy, knows it will be a string userRows[0].get('badColumn'); // <- will throw a type error ``` -------------------------------- ### loadInfo() Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Loads basic document properties and child sheets. This method populates the props and sheets properties of the spreadsheet object. ```APIDOC ## loadInfo() ### Description Load basic document props and child sheets. ### Method async ### Side Effects props are populated, sheets are populated ``` -------------------------------- ### searchDeveloperMetadata(filters) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Searches for developer metadata entries that match the provided filters. Returns an array of matching DeveloperMetadata objects. ```APIDOC ## searchDeveloperMetadata(filters) ### Description Search for developer metadata entries matching the given filters. ### Method async ### Parameters #### Request Body - **filters** (Array<[DataFilter](https://developers.google.com/sheets/api/reference/rest/v4/DataFilter)>) - Required - Array of DataFilter objects to match against. ### Returns - `Promise` - array of matching [DeveloperMetadata](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata#DeveloperMetadata) objects ### Request Example ```javascript const results = await doc.searchDeveloperMetadata([ { developerMetadataLookup: { metadataKey: 'my-key' } }, ]); ``` ``` -------------------------------- ### Accessing and Modifying Row Data (Before) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/migration-guide.md Illustrates the previous row-based API using dynamic getters and setters. ```javascript console.log(row.first_name); row.email = 'theo@example.com'; Object.assign(row, { first_name: 'Theo', email: 'theo@example.com' }) ``` -------------------------------- ### Saving and Deleting Rows Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-row.md Explains how to persist changes made to a row and how to delete a row from the sheet. ```APIDOC ## save(options) ### Description Save any updates made to row values ### Parameters #### Path Parameters - **options** (Object) - Description: Options object - **options.raw** (Boolean) - Description: Store raw values instead of converting as if typed into the sheets UI _see [ValueInputOption](https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption)_ - ✨ **Side effects** - updates are saved and everything re-fetched from google ## delete() ### Description Delete this row - ✨ **Side effects** - Row is removed from the sheet. Later rows that have been loaded have their `rowNumber` shifted accordingly. _also available as `row.del()`_ ``` -------------------------------- ### Loading Worksheets from a Google Spreadsheet Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Demonstrates how to load worksheet information from a Google Spreadsheet document. You can access worksheets by their index or ID, or add a new worksheet to the document. ```javascript const doc = new GoogleSpreadsheet('', auth); await doc.loadInfo(); // loads sheets and other document metadata const firstSheet = doc.sheetsByIndex[0]; // in the order they appear on the sheets UI const sheet123 = doc.sheetsById[123]; // accessible via ID if you already know it const newSheet = await doc.addSheet(); // adds a new sheet ``` -------------------------------- ### createDeveloperMetadata(developerMetadata) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Creates new developer metadata associated with a sheet or range. ```APIDOC ## createDeveloperMetadata(developerMetadata) ### Description Creates developer metadata. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **developerMetadata** (Object) - Required - The developer metadata to create. This object can include: - **metadataKey** (String) - Required - The key of the metadata. - **metadataValue** (String) - Optional - The value of the metadata. - **location** (Object) - Optional - Where the metadata is attached. - **visibility** (String) - Optional - Who can access the metadata: 'DOCUMENT' or 'PROJECT'. ### Request Example ```json { "developerMetadata": { "metadataKey": "myKey", "metadataValue": "myValue", "location": { "dimensionRange": { "sheetId": 0, "startRowIndex": 1, "endRowIndex": 2 } }, "visibility": "DOCUMENT" } } ``` ### Response #### Success Response (200) - None explicitly documented, but the operation has side effects. ### Side Effects - Developer metadata is created. ``` -------------------------------- ### resize(props) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md A shortcut method to update the grid properties, specifically row and column counts. It internally calls `updateProperties` with `gridProperties`. ```APIDOC ## resize(props) ### Description Updates the grid properties (row and column counts) of the worksheet. This is a convenience method that calls `sheet.updateProperties()` internally. ### Method `async resize(props: object)` ### Parameters #### Request Body - **props** (object) - Required - An object containing grid properties to update, such as `rowCount` and `columnCount`. - **rowCount** (number) - Optional - The desired number of rows. - **columnCount** (number) - Optional - The desired number of columns. ### Request Example ```javascript await sheet.resize({ rowCount: 1000, columnCount: 20 }); ``` ### Response - ✨ **Side Effects -** grid properties / dimensions are updated ``` -------------------------------- ### List Spreadsheet Permissions Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Retrieves all permission entries for a given Google Spreadsheet. Ensure Drive API scopes are included during authentication. ```javascript const permissions = await doc.listPermissions(); ``` -------------------------------- ### Formatting Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Method for updating borders within a specified range on the worksheet. ```APIDOC ## updateBorders(range, borders) ### Description Updates borders for a range. ### Parameters #### Path Parameters - **range** (Object<[GridRange]>) - Required - The range whose borders should be updated, sheetId not required - **borders** (Object) - Optional - Border styles - **borders.top** (Object<[Border]>) - Optional - Top border style - **borders.bottom** (Object<[Border]>) - Optional - Bottom border style - **borders.left** (Object<[Border]>) - Optional - Left border style - **borders.right** (Object<[Border]>) - Optional - Right border style - **borders.innerHorizontal** (Object<[Border]>) - Optional - Inner horizontal border style - **borders.innerVertical** (Object<[Border]>) - Optional - Inner vertical border style ### Side Effects Borders are updated on the sheet. ``` -------------------------------- ### Loading Cells in a Worksheet Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-cell.md Demonstrates how to load a specific range of cells from a Google Spreadsheet worksheet and access individual cells using row/column indices or A1 notation. Ensure you have authenticated and loaded the spreadsheet and sheet information first. ```javascript const doc = new GoogleSpreadsheet('', auth); await doc.loadInfo(); // loads sheets const sheet = doc.sheetsByIndex[0]; // the first sheet await sheet.loadCells('A1:D5'); const cellA1 = sheet.getCell(0, 0); const cellC3 = sheet.getCellByA1('C3'); ``` -------------------------------- ### share(emailAddressOrDomain, options?) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Shares the Google Sheet with a specific email address or domain. Requires Drive API scopes. ```APIDOC ## share(emailAddressOrDomain, options?) ### Description Shares the Google Sheet with a specific email address or domain. ### Method `async` ### Parameters #### Path Parameters - **emailAddressOrDomain** (string) - Required - The email address or domain to share with. #### Query Parameters - **options** (object) - Optional - Configuration for sharing. - **role** (string) - Optional - The role to grant. Possible values: `owner` (transfers ownership, only for single users), `writer` (allows writing, commenting, reading), `commenter` (allows reading and commenting), `reader` (allows reading only). - **isGroup** (boolean) - Optional - Set to `true` if sharing with an email that refers to a group. - **emailMessage** (string or false) - Optional - A custom message to include in the email notification. Set to `false` to disable email notifications entirely. If not provided, a default message is sent. ### Example ```js // Share with a user with read-only access await doc.share('user@example.com', { role: 'reader' }); // Share with a domain with writer access, including a custom message await doc.share('example.com', { role: 'writer', emailMessage: 'Here is the document for collaboration.' }); // Share with a group without sending an email notification await doc.share('group@example.com', { role: 'commenter', isGroup: true, emailMessage: false }); ``` ``` -------------------------------- ### clearAllFormatting() Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-cell.md Resets all cell formatting to the default. This is a local change and requires saving to persist. ```APIDOC ## clearAllFormatting() ### Description Resets all cell formatting to default/nothing. This is a local change and must still be saved. ### Method `clearAllFormatting()` ### Side Effects All user-entered format settings are cleared (locally). ``` -------------------------------- ### Authenticate with Service Account Impersonation Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/authentication.md Use this for domain-wide delegation, allowing your service account to impersonate a specific user within your organization. The service account must have domain-wide delegation enabled. ```javascript const jwtWithImpersonation = new JWT({ email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL, key: process.env.GOOGLE_PRIVATE_KEY, subject: 'user.to.impersonate@mycompany.com', scopes: SCOPES, }); ``` -------------------------------- ### downloadAsPDF Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Exports the worksheet data in PDF format. You can choose to receive the data as a Buffer or a stream. ```APIDOC ## downloadAsPDF(returnStreamInsteadOfBuffer) ### Description Export worksheet in PDF format. ### Parameters #### Query Parameters - **returnStreamInsteadOfBuffer** (Boolean) - Optional - Set to true to return a stream instead of a Buffer. See [Exports guide](guides/exports) for more details. ### Returns - Buffer (or stream) containing PDF data ``` -------------------------------- ### Search Developer Metadata Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Searches for developer metadata entries using provided filters. Requires drive scopes. ```javascript const results = await doc.searchDeveloperMetadata([ { developerMetadataLookup: { metadataKey: 'my-key' } }, ]); ``` -------------------------------- ### Adding, Appending, Reading, and Modifying Rows Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/README.md Shows how to add a new sheet with header values, append single or multiple rows, read all rows, and update or delete individual rows. Supports explicit TypeScript types for row data. ```javascript // if creating a new sheet, you can set the header row const sheet = await doc.addSheet({ headerValues: ['name', 'email'] }); // append rows const larryRow = await sheet.addRow({ name: 'Larry Page', email: 'larry@google.com' }); const moreRows = await sheet.addRows([ { name: 'Sergey Brin', email: 'sergey@google.com' }, { name: 'Eric Schmidt', email: 'eric@google.com' }, ]); // read rows const rows = await sheet.getRows(); // can pass in { limit, offset } // read/write row values console.log(rows[0].get('name')); // 'Larry Page' rows[1].set('email', 'sergey@abc.xyz'); // update a value rows[2].assign({ name: 'Sundar Pichai', email: 'sundar@google.com' }); // set multiple values await rows[2].save(); // save updates on a row await rows[2].delete(); // delete a row ``` ```typescript type UsersRowData = { name: string; email: string; type?: 'admin' | 'user'; }; const userRows = await sheet.getRows(); userRows[0].get('name'); // <- TS is happy, knows it will be a string userRows[0].get('badColumn'); // <- will throw a type error ``` -------------------------------- ### autoFill Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Auto-fills cells with data following a pattern, similar to dragging the fill handle in a spreadsheet. It can accept either a GridRange or a SourceAndDestination object to define the area for auto-filling. ```APIDOC ## autoFill(rangeOrSource, useAlternateSeries) ### Description Auto-fills cells with data following a pattern (like dragging the fill handle). ### Method async ### Parameters #### Path Parameters - **rangeOrSource** (Object<[GridRange](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#GridRange) or [SourceAndDestination](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#SourceAndDestination)>) - Required - Either a range (auto-detects source) or explicit source/destination spec, sheetId not required - **useAlternateSeries** (Boolean) - Optional - Whether to generate data with the alternate series ### Side Effects - Cells are filled with pattern-based data. ### Warning - Does not update cached rows/cells, so be sure to reload rows/cells before accessing filled data. ``` -------------------------------- ### loadCells Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Fetches cells from the Google Sheet into a local cache. Filters can be applied to specify which cells to load, including A1 ranges, GridRange objects, or DeveloperMetadataLookup filters. If no filter is provided, all cells in the sheet are loaded. Note that this method does not return the cells directly but populates an internal cache. ```APIDOC ## loadCells(filters) ### Description Fetch cells from google into a local cache. Filters can be applied to specify which cells to load. ### Method `loadCells(filters)` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **filters** (any | Array) - Optional - Can be a single filter or array of filters. Filters can be A1 ranges, GridRange objects, or DeveloperMetadataLookup filters. ### Request Example ```javascript await sheet.loadCells(); // no filter - will load ALL cells in the sheet await sheet.loadCells('B2:D5'); // A1 range await sheet.loadCells({ startRowIndex: 5, endRowIndex: 100, startColumnIndex:0, endColumnIndex: 200 }); // GridRange object await sheet.loadCells({ startRowIndex: 50 }); // not all props required await sheet.loadCells(['B2:D5', 'B50:D55']); // can pass an array of filters await sheet.loadCells({ developerMetadataLookup: { metadataKey: 'my-key' } }); // DeveloperMetadataLookup filter ``` ### Response #### Success Response This method does not return the cells it loads; instead, they are kept in a local cache managed by the sheet. `cellStats` is updated. #### Response Example None (operates via side effects on local cache) ``` -------------------------------- ### Conditional Formatting Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Manage conditional formatting rules on a worksheet, including adding, updating, and deleting them. ```APIDOC ## addConditionalFormatRule(rule, index) ### Description Adds a new conditional formatting rule at the given index. ### Method (async) ### Parameters #### Request Body - **rule** (Object<[ConditionalFormatRule]>): Required - The rule to add. - **rule.ranges** (Array<[GridRange]>): Optional - The ranges that are formatted if the condition is true. - **rule.booleanRule** (Object<[BooleanRule]>): Optional - The formatting is either 'on' or 'off'. - **rule.gradientRule** (Object<[GradientRule]>): Optional - The formatting will vary based on gradients. - **index** (Integer): Required - The zero-based index where the rule should be inserted. ### Side Effects - Conditional format rule is added, all subsequent rules' indexes are incremented. ``` ```APIDOC ## updateConditionalFormatRule(options) ### Description Updates a conditional format rule at the given index, or moves it to another index. ### Method (async) ### Parameters #### Request Body - **options.index** (Integer): Required - The zero-based index of the rule. - **options.rule** (Object<[ConditionalFormatRule]>): Optional - The rule to replace at the given index (mutually exclusive with newIndex). - **options.newIndex** (Integer): Optional - The zero-based new index the rule should end up at (mutually exclusive with rule). - **options.sheetId** (Integer): Optional - The sheet of the rule to move (required if newIndex is set). ### Side Effects - Conditional format rule is updated or moved. ``` ```APIDOC ## deleteConditionalFormatRule(index, sheetId) ### Description Deletes a conditional format rule at the given index. ### Method (async) ### Parameters #### Path Parameters - **index** (Integer): Required - The zero-based index of the rule to be deleted. - **sheetId** (Integer): Optional - The sheet the rule is being deleted from (defaults to this sheet). ### Side Effects - Conditional format rule is deleted, all subsequent rules' indexes are decremented. ``` -------------------------------- ### autoResizeDimensions(columnsOrRows, rangeIndexes?) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Automatically resizes rows or columns to fit their content, similar to the 'Fit to data' option in the Google Sheets UI. ```APIDOC ## autoResizeDimensions(columnsOrRows, rangeIndexes?) ### Description Automatically adjusts the size of rows or columns to fit their content, mimicking the 'Fit to data' functionality in the Google Sheets interface. ### Method `async autoResizeDimensions(columnsOrRows: string, rangeIndexes?: object)` ### Parameters #### Path Parameters - **columnsOrRows** (string) - Required - Specifies whether to auto-resize 'COLUMNS' or 'ROWS'. - **rangeIndexes** (object) - Optional - Specifies a range to limit the auto-resizing operation. - **startIndex** (number) - Optional - The starting row/column index (inclusive). - **endIndex** (number) - Optional - The ending row/column index (exclusive). ### Response - ✨ **Side effects** - rows or columns are resized to fit their content ``` -------------------------------- ### Accessing and Modifying Row Data (After) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/guides/migration-guide.md Shows the updated row-based API using explicit get/set functions for better type safety and to avoid naming collisions. ```javascript console.log(row.get('first_name')); row.set('email', 'theo@example.com'); row.assign({ first_name: 'Theo', email: 'theo@example.com' }); ``` -------------------------------- ### cutPaste(source, destination, pasteType) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Moves data from a source range to a destination coordinate by cutting and pasting. This operation also requires a reload to ensure cached data reflects the changes. ```APIDOC ## cutPaste(source, destination, pasteType) ### Description Cuts data from a source range and pastes it to a destination coordinate. ### Parameters #### Path Parameters - **source** (Object<[GridRange]>): Required - The source range to cut from, sheetId not required. - **destination** (Object<[GridCoordinate]>): Required - The top-left coordinate where data should be pasted, sheetId not required. - **destination.rowIndex** (Number= 0>): Required - The row index (0-based). - **destination.columnIndex** (Number= 0>): Required - The column index (0-based). - **pasteType** (String (enum)<[PasteType]>): Optional - What kind of data to paste. _defaults to `PASTE_NORMAL`_. ### Side Effects - Data is moved from source to destination. ### Warning - Does not update cached rows/cells, so be sure to reload rows/cells before accessing moved data. ``` -------------------------------- ### Set Public Access Level for Spreadsheet Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md Configures the public access level for a Google Spreadsheet. Use 'false' to revoke all public access. Users still need to be logged in to access the document. ```javascript await doc.setPublicAccessLevel('reader'); // Example: set to reader role ``` -------------------------------- ### getRows Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Fetches rows from the sheet. Supports skipping a number of rows and limiting the number of rows fetched. ```APIDOC ## getRows(options) ### Description Fetch rows from the sheet. ### Parameters #### Path Parameters - **options** (Object) - Optional - Options object. - **options.offset** (Number) - Optional - How many rows to skip from the top. - **options.limit** (Number) - Optional - Max number of rows to fetch. ### Returns - [[GoogleSpreadsheetRow]] (in a promise) ### Note The older version of this module allowed you to filter and order the rows as you fetched them, but this is no longer supported by google. ``` -------------------------------- ### downloadAsTSV Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Exports the worksheet data in TSV format. You can choose to receive the data as a Buffer or a stream. ```APIDOC ## downloadAsTSV(returnStreamInsteadOfBuffer) ### Description Export worksheet in TSV format. ### Parameters #### Query Parameters - **returnStreamInsteadOfBuffer** (Boolean) - Optional - Set to true to return a stream instead of a Buffer. See [Exports guide](guides/exports) for more details. ### Returns - Buffer (or stream) containing TSV data ``` -------------------------------- ### Filters Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Methods for setting and clearing the basic filter on a worksheet. ```APIDOC ## setBasicFilter(filter) ### Description Sets the basic filter on this sheet. ### Parameters #### Path Parameters - **filter** (Object) - Optional - Basic filter configuration - **filter.range** (Object<[GridRange]>) - Optional - Range to filter, sheetId not required - **filter.sortSpecs** (Array of [SortSpec]) - Optional - Sort specifications - **filter.filterSpecs** (Array) - Optional - Filter specifications per column ### Side Effects Basic filter is applied to the sheet. ``` ```APIDOC ## clearBasicFilter() ### Description Clears the basic filter on this sheet. ### Side Effects Basic filter is removed from the sheet. ``` -------------------------------- ### copyPaste(source, destination, pasteType, pasteOrientation) Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Copies data from a source range to a destination range. Supports different paste types and orientations (normal or transposed). The operation affects the sheet directly, and a reload is recommended for updated data access. ```APIDOC ## copyPaste(source, destination, pasteType, pasteOrientation) ### Description Copies data from a source range and pastes it to a destination range. ### Parameters #### Path Parameters - **source** (Object<[GridRange]>): Required - The source range to copy from, sheetId not required. - **destination** (Object<[GridRange]>): Required - The destination range to paste to, sheetId not required. - **pasteType** (String (enum)<[PasteType]>): Optional - What kind of data to paste. _defaults to `PASTE_NORMAL`_. - **pasteOrientation** (String (enum)): Optional - NORMAL or TRANSPOSE. _defaults to `NORMAL`_. ### Side Effects - Data is copied to the destination range. ### Warning - Does not update cached rows/cells, so be sure to reload rows/cells before accessing pasted data. ``` -------------------------------- ### downloadAsCSV Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-worksheet.md Exports the worksheet data in CSV format. You can choose to receive the data as a Buffer or a stream. ```APIDOC ## downloadAsCSV(returnStreamInsteadOfBuffer) ### Description Export worksheet in CSV format. ### Parameters #### Query Parameters - **returnStreamInsteadOfBuffer** (Boolean) - Optional - Set to true to return a stream instead of a Buffer. See [Exports guide](guides/exports) for more details. ### Returns - Buffer (or stream) containing CSV data ``` -------------------------------- ### save() Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet-cell.md Saves the individual cell's updates. This operation fetches updated data from Google. It's often more efficient to use `sheet.saveUpdatedCells()` for multiple cell updates. ```APIDOC ## save() ### Description Saves this individual cell. Updates are saved and everything is re-fetched from Google. ### Method `save()` ### Side Effects Updates are saved and everything re-fetched from Google. ### Note Usually makes more sense to use `sheet.saveUpdatedCells()` to save many cell updates at once. ``` -------------------------------- ### GoogleSpreadsheet.createNewSpreadsheetDocument Source: https://github.com/theoephraim/node-google-spreadsheet/blob/main/docs/classes/google-spreadsheet.md A static asynchronous method to create a new Google Spreadsheet document with specified properties and authentication. The created document is owned by the authenticated user. ```APIDOC ## `GoogleSpreadsheet.createNewSpreadsheetDocument(auth, properties)` (async) ### Description Create a new Google Spreadsheet document with the provided authentication and properties. The document will be owned by the authenticated user. ### Parameters #### Path Parameters - **auth** (Auth) - Required - The authentication object to use when creating the document. See [Authentication](guides/authentication) for more info. - **properties** (Object) - Optional - Properties to use when creating the new document. See [basic document properties](#basic-document-properties) for more details. ### Returns - Promise<[GoogleSpreadsheet]> - A Promise that resolves with a GoogleSpreadsheet instance, with auth set, id and info loaded. ### Warning The document will be owned by the authenticated user, which depending on the auth you are using, could be a service account. In this case the sheet may not be accessible to you personally. ### Side Effects All info (including `spreadsheetId`) and sheets loaded as if you called [`loadInfo()`](#fn-loadInfo). ### Request Example ```javascript // see Authentication for more info on auth and how to create jwt const doc = await GoogleSpreadsheet.createNewSpreadsheetDocument(jwt, { title: 'This is a new doc' }); console.log(doc.spreadsheetId); const sheet1 = doc.sheetsByIndex[0]; ``` ```