Skip to content

Instantly share code, notes, and snippets.

@king-panda
Last active October 30, 2016 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save king-panda/17ddbd29f75efc224a9d to your computer and use it in GitHub Desktop.
Save king-panda/17ddbd29f75efc224a9d to your computer and use it in GitHub Desktop.
【GAS】スプレッドシートのデータをJSON出力する関数をExecution APIで外部のNode.jsから実行する ref: http://qiita.com/kingpanda/items/8e60a64dc2454f6ae6b5
npm install googleapis --save
npm install google-auth-library --save
resource: {
function: 'doOutput',
//body:'hogehoge'
},
node quickstart.js
[
{
"名前": "鷲尾伶菜",
"年齢": 21,
"備考": "ボーカル&パフォーマー"
},
{
"名前": "藤井萩花",
"年齢": 20,
"備考": "パフォーマー"
},
{
"名前": "中島美央",
"年齢": 21,
"備考": "パフォーマー"
},
{
"名前": "重留真波",
"年齢": 20,
"備考": "リーダー&パフォーマー"
},
{
"名前": "坂東希",
"年齢": 18,
"備考": "パフォーマー"
},
{
"名前": "佐藤晴美",
"年齢": 20,
"備考": "パフォーマー"
}
]
var url = 'https://docs.google.com/spreadsheets/d/***スプレッドシートID***/pubhtml';
var sheetName = '***シート名***';
var book = SpreadsheetApp.openByUrl(url);
var sheet = book.getSheetByName(sheetName);
function doOutput(e){
var json = convSheet(sheet);
Logger.log(JSON.stringify(json));
return JSON.stringify(json);
}
function convSheet(sheet) {
var colStartIndex = 1;
var rowNum = 1;
var firstRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
var firstRowValues = firstRange.getValues();
var titleColumns = firstRowValues[0];
var lastRow = sheet.getLastRow();
var rowValues = [];
for(var rowIndex=2; rowIndex<=lastRow; rowIndex++) {
var colStartIndex = 1;
var rowNum = 1;
var range = sheet.getRange(rowIndex, colStartIndex, rowNum, sheet.getLastColumn());
var values = range.getValues();
rowValues.push(values[0]);
}
var jsonArray = [];
for(var i=0; i<rowValues.length; i++) {
var line = rowValues[i];
var json = new Object();
for(var j=0; j<titleColumns.length; j++) {
json[titleColumns[j]] = line[j];
}
jsonArray.push(json);
}
return jsonArray;
}
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'script-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Apps Script Execution API.
authorize(JSON.parse(content), callAppsScript);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.web.client_secret;
var clientId = credentials.web.client_id;
var redirectUrl = credentials.web.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Call an Apps Script function to list the folders in the user's root
* Drive folder.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function callAppsScript(auth) {
var scriptId = '***scriptId***';
var script = google.script('v1');
// Make the API request. The request object is included here as 'resource'.
script.scripts.run({
auth: auth,
resource: {
function: 'doOutput'
},
scriptId: scriptId
}, function(err, resp) {
if (err) {
// The API encountered a problem before the script started executing.
console.log('The API returned an error: ' + err);
return;
}
if (resp.error) {
// The API executed, but the script returned an error.
// Extract the first (and only) set of error details. The values of this
// object are the script's 'errorMessage' and 'errorType', and an array
// of stack trace elements.
var error = resp.error.details[0];
console.log('Script error message: ' + error.errorMessage);
console.log('Script error stacktrace:');
if (error.scriptStackTraceElements) {
// There may not be a stacktrace if the script didn't start executing.
for (var i = 0; i < error.scriptStackTraceElements.length; i++) {
var trace = error.scriptStackTraceElements[i];
console.log('\t%s: %s', trace.function, trace.lineNumber);
}
}
} else {
// The structure of the result will depend upon what the Apps Script
// function returns. Here, the function returns an Apps Script Object
// with String keys and values, and so the result is treated as a
// Node.js object (folderSet).
var folderSet = resp.response.result;
console.log(resp.response.result);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment