Google apps script update fusion table from spreadsheet script

不想你离开。 提交于 2019-11-29 00:42:48

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......';

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