Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active Jul 21, 2019
Embed
What would you like to do?
Creating a Table to Google Document by Retrieving Values from Google Spreadsheet for Node.js

Creating a Table to Google Document by Retrieving Values from Google Spreadsheet for Node.js

This is a sample script for creating a table to Google Document by retrieving values from Google Spreadsheet for Node.js.

Before you use this script, please install Node.js module of node-gdoctableapp.

$ npm install --save-dev gdoctableapp

or

$ npm install --global gdoctableapp

Sample script:

This sample script uses Service Account.

In this sample script, the values are retrieved from Sheet1!A1:C5 of Spreadsheet, and new table is created to the Document using the values.

const { google } = require("googleapis");
const gdoctableapp = require("gdoctableapp");
const key = require("credential.json"); // Please set the json file of Service account.

const jwtClient = new google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  [
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/spreadsheets"
  ],
  null
);

const sheets = google.sheets({ version: "v4", auth: jwtClient });

const spreadsheetId = "###"; // Please set here
const documentId = "###"; // Please set here

sheets.spreadsheets.values.get(
  {
    spreadsheetId: spreadsheetId,
    range: "Sheet1!A1:C5"
  },
  (err, res) => {
    if (err) {
      console.log(err.errors);
      return;
    }
    const values = res.data.values;
    if (values.length) {
      const resource = {
        auth: jwtClient,
        documentId: documentId,
        rows: values.length,
        columns: values[0].length,
        append: true,
        values: values
      };
      gdoctableapp.CreateTable(resource, function(er, re) {
        if (er) {
          console.log(er.errors);
          return;
        }
        console.log(re);
      });
    } else {
      console.log("No data was found.");
    }
  }
);

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment