导入私人谷歌融合表到谷歌文档电子表格

时间:2011-11-14 18:38:02

标签: urlfetch google-spreadsheet-api google-fusion-tables

我想为google fusion table构建一个图表。我知道有一个选项可以使用融合表进行,但我需要使用谷歌电子表格。

如何将私有融合表导入电子表格?

function getdata(authToken) {
      query = encodeURIComponent("SELECT * FROM tableid");
      var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
      var response = UrlFetchApp.fetch(URL, {
         method: "get",
         headers: {
              "Authorization": "GoogleLogin auth=" + authToken,
         }
      });
      return response.getContentText();
}

上面的代码只给我表格标题。

3 个答案:

答案 0 :(得分:1)

除非您需要处理每一位数据,否则不要像以下示例中那样单独设置每个单元格。使用它大约快10倍:

var rows = o.length;
var columns = o[0].length;
cell.offset(<startrow>, <startcolumn>, rows, columns).setValues(o);

答案 1 :(得分:0)

经过深入研究后,我终于在经过深入搜索和阅读here后想出来了。 这是它如何查找代码谷歌文档电子表格应用程序脚本:

function onOpen()
{
  var tableID = '00000' // 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);
  query = encodeURIComponent("SELECT * FROM tableID");
  var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;

  var response = UrlFetchApp.fetch(URL, {
     method: "get",
     headers: {
          "Authorization": "GoogleLogin auth=" + authToken,
     }
  });
  var tableData = response.getContentText();
  var o  = Utilities.parseCsv(response.getContentText());
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var cell = doc.getRange('a1');
  var index = 0;
  for (var i in o) {
    var row = o[i];
    var col = 0;
    for (var j in row) {
      cell.offset(index, col).setValue(row[j]);
      col++;
    }
    index++;
  }
}

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;
}

之后,您可以在电子表格中执行任何操作。 顺便说一句,我仍然认为有一种简单的方法可以自动将私人表格导入电子表格。

答案 2 :(得分:-1)

有一篇很好的文章描述了如何从Apps脚本访问Fusion Tables:

http://googleappsdeveloper.blogspot.com/2011/09/using-fusion-tables-with-apps-script.html

有一些示例代码的链接,您可以调整这些代码以将Fusion Table数据导入电子表格。