简体   繁体   中英

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);

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,
};

To add to ziganotschka's answer above. It looks like request.resource is now outdated in v4 as of around Feb 2020 and it's now necessary to use request.requestBody instead.

Updated Sample:

const request = {
  spreadsheetId: "my-spreadsheet-id",
  range: "Sheet1!A:E",
  valueInputOption: "USER_ENTERED",
  requestBody: {values: [
    [1, 2],
    [3, 4],
  ]},
  auth: authClient,
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM