Skip to content
Advertisement

Google Sheets API v4 write data

I am trying to write data to a Google Sheet using the Nodejs API v4. I can sucessfully read and clear data, so I have set everything up correctly. However, using the example in the docs here for the update method, I cannot work out how to specify the data I want to put in the Google sheet. I would like an example showing how to paste the data held by const data into the sheet specified. Here is what I have so far:

const data = [
  [1, 2],
  [3, 4],
];
const auth = new google.auth.GoogleAuth({
  scopes: ["https://www.googleapis.com/auth/spreadsheets"],
});
const authClient = await auth.getClient();
const sheets = google.sheets({ version: "v4", auth: authClient });
const request = {
  spreadsheetId: "my-spreadsheet-id",
  range: "Sheet1!A:E",
  valueInputOption: "",
  resource: {},
  auth: authClient,
};
const response = await sheets.spreadsheets.values.update(request);

Advertisement

Answer

You must specify a value input option

Possible values are:

  • USER_ENTERED
  • RAW
  • INPUT_VALUE_OPTION_UNSPECIFIED

The resource is your data array.

Sample:

const request = {
  spreadsheetId: "my-spreadsheet-id",
  range: "Sheet1!A:E",
  valueInputOption: "USER_ENTERED",
  resource: {values: [
    [1, 2],
    [3, 4],
  ]},
  auth: authClient,
};
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement