Hi Everyone
Does anyone have a procedure or a code I can follow to have Google Apps Script parse data in google sheets over to smartsheet? I have been using this code below but the data still isn't appearing in smartsheet. I know I could be using zapier but I would prefer to use Apps Script so everything is dedicated on Googles backend.
Thanks for any help you can offer or even supply a code I can use. - John
function getDataFromGoogleSheet() {
try {
// Replace 'YOUR_SPREADSHEET_ID' with the actual ID of your Google Sheet
var spreadsheetId = 'YOUR_SPREADSHEET_ID';
// Replace 'Sheet1' with the name of the sheet containing your data
var sheetName = 'SHEET1';
var sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName);
var data = sheet.getDataRange().getValues();
// Log the data to ensure it's fetched correctly
Logger.log(data);
// Return the data
return data;
} catch (error) {
Logger.log("Error in getDataFromGoogleSheet: " + error.toString());
return []; // Return an empty array if there's an error
}
}
function sendDataToSmartsheet(data) {
try {
// Replace 'YOUR_SMARTSHEET_ACCESS_TOKEN' with your Smartsheet API access token
var accessToken = 'YOUR_SMARTSHEET_ACCESS_TOKEN';
// Replace 'YOUR_SMARTSHEET_SHEET_ID' with the actual ID of your Smartsheet
var smartsheetSheetId = 'YOUR_SMARTSHEET_SHEET_ID';
// Construct the API URL
var apiUrl = 'https://api.smartsheet.com/2.0/sheets/' + smartsheetSheetId + '/rows';
// Log the data to ensure it's not undefined
Logger.log("Data received: " + JSON.stringify(data));
// Check if data is not undefined and has a length property
if (data && data.length) {
// Prepare the data payload for Smartsheet
var payload = {
"toBottom": true,
"cells": []
};
// Loop through the data and add each row to the payload
for (var i = 0; i < data.length; i++) {
var row = data[i];
var rowData = [];
// Add each cell value to the rowData array
for (var j = 0; j < row.length; j++) {
rowData.push({ "columnId": j + 1, "value": row[j] });
}
// Add the rowData to the cells array in the payload
payload.cells.push(rowData);
}
// Set the options for the HTTP request to Smartsheet
var options = {
'method': 'post',
'headers': {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json',
},
'payload': JSON.stringify(payload)
};
// Make the HTTP request to Smartsheet
var response = UrlFetchApp.fetch(apiUrl, options);
// Log the response to check for errors
Logger.log("Response from Smartsheet API: " + response);
} else {
Logger.log("Error: Data is undefined or has no length.");
}
} catch (error) {
Logger.log("Error in sendDataToSmartsheet: " + error.toString());
}
}
function runScript() {
var data = getDataFromGoogleSheet();
sendDataToSmartsheet(data);
}