📅  最后修改于: 2023-12-03 15:01:03.001000             🧑  作者: Mango
When working with Google Sheets in TypeScript, it can sometimes be tricky to add a new line to the sheet. In this guide, we'll show you how to add a new line to a Google Sheet in TypeScript.
Before we get started, you'll need the following:
To add a new line to a Google Sheet in TypeScript, we'll need to use the Google Sheets API. Here's an example of how to do this:
import { google } from 'googleapis';
// Authenticate with Google Sheets
const auth = new google.auth.GoogleAuth({
keyFile: 'path/to/keyfile.json',
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
// Create a Sheets API client
const sheets = google.sheets({
version: 'v4',
auth,
});
// Define the spreadsheet ID and sheet name
const spreadsheetId = 'your_spreadsheet_id';
const sheetName = 'your_sheet_name';
// Define the value to insert in the new row
const valuesToInsert = ['Hello', 'World'];
// Define the range for the new row
const range = `${sheetName}!A1`;
// Add the new row to the sheet
await sheets.spreadsheets.values.append({
spreadsheetId,
range,
valueInputOption: 'USER_ENTERED',
resource: {
values: [valuesToInsert],
},
});
Let's walk through the code to better understand what's happening.
First, we authenticate with Google Sheets using a keyfile and the appropriate scopes:
const auth = new google.auth.GoogleAuth({
keyFile: 'path/to/keyfile.json',
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
Next, we create a Sheets API client:
const sheets = google.sheets({
version: 'v4',
auth,
});
We need to define the ID of the spreadsheet we want to add a new line to, as well as the name of the sheet:
const spreadsheetId = 'your_spreadsheet_id';
const sheetName = 'your_sheet_name';
We need to define the value we want to insert into the new row:
const valuesToInsert = ['Hello', 'World'];
Now we need to define the range where the new row will be inserted. In this example, we're inserting the new row at the top of the sheet (A1).
const range = `${sheetName}!A1`;
Finally, we can add the new row to the sheet:
await sheets.spreadsheets.values.append({
spreadsheetId,
range,
valueInputOption: 'USER_ENTERED',
resource: {
values: [valuesToInsert],
},
});
We use the append
method of the spreadsheets.values
resource to add the new row. We pass in the spreadsheet ID, range, value input option, and the values we want to insert.
Adding a new line to a Google Sheet in TypeScript is relatively simple once you understand how to use the Google Sheets API. By using the spreadsheets.values.append
method, you can easily insert a new row into a sheet.