Google apps script update fusion table from spreadsheet script

冷暖自知 提交于 2019-11-27 15:23:33

问题


I would like to create an apps script in a google docs spreadsheet that will periodically copy rows from the sheet and insert them into a fusion table. Below I've pasted my best attempt, but it should be noted that I really want it to be posting a 2 column range, not that pair of values. That is just a placeholder.

This link here describes how to talk to fusion tables http://code.google.com/apis/fusiontables/docs/developers_guide.html#Inserting

But I dont understand how to write the script to achieve this. I've messed around with it a bunch and I think I have these problems

-I'm not forming the post request correctly -I'm missing some sort of authentication step.

I am a total newb and what I have here is copy pasted. A few resources that looked helpful:

This guy seems to have figured out how to write an app script to send post requests http://blog.vivekhaldar.com/post/428652690/google-apps-script-spreadsheets-mashup-hub

This seems to be important

http://code.google.com/googleapps/appsscript/class_urlfetchapp.html

these people seem to be doing somthing very similiar, but I cant figure out how to make it work

http://groups.google.com/group/fusion-tables-users-group/browse_thread/thread/99db4db33e405f01


function deet() {
  var advancedArgs = {
      method: "post", 
      payload: "?sql=" + "INSERT INTO 1299801(Text, Number) VALUES ('Blue Shoes', 50)", 
      headers: {"Authorization": "Basic <base64 encoding of your username:passwd"}};
  var response = UrlFetchApp.fetch(
      "https://www.google.com/fusiontables/api/query",advancedArgs);

}

Thanks in advance!


回答1:


Here's an updated version of a script that John McGrath via the Google Fusion Tables group authored to create a manual "sync" between a Google spreadsheet and a Google Fusion Table.

I've modified the script a bit for my needs and have added use of an API key and the new Fusion Tables API endpoint as the original version used the SQL API endpoint, which is being phased out.

To use, simply add your Fusion Table's encrypted table ID to the top of the script...

// Add the encrypted table ID of the fusion table here
var tableIDFusion = '17xnxY......';

And add your api key...

// key needed for fusion tables api
var fusionTablesAPIKey = '17xnxY......';



回答2:


This script wipes a Fusion Table and updates it with data from the first sheet in the spreadsheet. You need to create a named range (called "namedRange" but you can change this in the code). The row above the named range should be the headers. You also need to set the Table ID of the Fusion table you want to update, and you need to make sure the header names match the column names in the Fusion Table.

The script is a bit crude and lacks comments, but hopefully it will help you.

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [ {name: "Update Fusion Table", functionName: "updateFT"} ];
  ss.addMenu("Fusion Tables", menuEntries);
}

function updateFT() {
  var tableID = '99999' // Add the table ID of the fusion table here
      var email = UserProperties.getProperty('email');
  var password = UserProperties.getProperty('password');

  if (email === null || password === null) {
    email = Browser.inputBox('Enter email');
    password = Browser.inputBox('Enter password');
    UserProperties.setProperty('email',email);
    UserProperties.setProperty('password', password);
  } else {
    email = UserProperties.getProperty('email');
    password = UserProperties.getProperty('password');
  }
  var authToken = getGAauthenticationToken(email,password);
  deleteData(authToken, tableID);
  var updateMsg = updateData(authToken, tableID);
  var updatedRowsCount = updateMsg.split(/\n/).length - 2;
  Browser.msgBox("Fusion Tables Update", "Updated " + updatedRowsCount + " rows in the Fusion Table", Browser.Buttons.OK);  
}


function getGAauthenticationToken(email, password) {
  password = encodeURIComponent(password);
  var response = UrlFetchApp.fetch("https://www.google.com/accounts/ClientLogin", {
    method: "post",
    payload: "accountType=GOOGLE&Email=" + email + "&Passwd=" + password + "&service=fusiontables&Source=testing"
  });
  var responseStr = response.getContentText();
  responseStr = responseStr.slice(responseStr.search("Auth=") + 5, responseStr.length);
  responseStr = responseStr.replace(/\n/g, "");
  return responseStr;
}

function queryFusionTables(authToken, query) {
  var URL = "http://www.google.com/fusiontables/api/query";
  var response = UrlFetchApp.fetch(URL, {
    method: "post",
    headers: {
      "Authorization": "GoogleLogin auth=" + authToken,
    },
    payload: "sql=" + query
  });
  return response.getContentText();
}

function deleteData(authToken, tableID) {
  var query = encodeURIComponent("DELETE FROM " + tableID);
  return queryFusionTables(authToken, query);
}

function updateData(authToken, tableID) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var blockDataRange = ss.getRangeByName('namedRange');
  var query = constructQuery(ss, blockDataRange, tableID);
  //  Browser.msgBox(query);
  return queryFusionTables(authToken, query);
}

function constructQuery(ss, range, tableID, columnHeadersRowIndex) {
  var sheet = ss.getSheets()[0];
  var columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
  var numColumns = range.getEndColumn() - range.getColumn() + 1;
  var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
  var headers = headersRange.getValues()[0];
  var data = range.getValues();
  var queryPrepend = "INSERT INTO " + tableID + " ("+headers.join(",") + ") VALUES ('";
  var query = "";

  for (var i = 0; i < data.length; ++i) {
    var hasData = false;
    if (isCellEmpty(data[i][0])) {
      continue;
    }
    query += queryPrepend + data[i].join("','") + "'); ";
  }
  return encodeURIComponent(query);
}

// Returns true if the cell where cellData was read from is empty.
// Arguments:
//   - cellData: string
function isCellEmpty(cellData) {
  return typeof(cellData) == "string" && cellData == "";
}


来源:https://stackoverflow.com/questions/7082611/google-apps-script-update-fusion-table-from-spreadsheet-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!