16

我正在我的 Google 站点上编写 Google Apps 脚本,并尝试使用在 Google 电子表格中的 2 个不同选项卡上提供的数据。从我认为我从文档中理解的内容来看,我可以SpreadsheetApp通过使用该方法在站点脚本上使用类中的所有可用openById()方法。

无论如何,这是我试图做的

function doGet(e) {

    var doc = SpreadsheetApp.openById(SPREADSHEET_ID_GOES_HERE).getActiveSheet();
    SpreadsheetApp.setActiveSheet(doc.getSheetId()[1]);

    //....
}

我得到错误

找不到方法 setActiveSheet(。(第 4 行)

我正在从这个链接中提取我的工作:Storing Data in Google Spreadsheets以及 Building User Interfaces 下列出的 Ui Service 部分。

有人看到我在这两行中做错了什么吗?

4

4 回答 4

25

setActiveSheet 只能用于 UI 显示的电子表格,即您在浏览器中打开的电子表格中的表格。

使用 SpreadsheetApp.openById 您正在打开一个电子表格以访问其数据,但它不会在您的浏览器中打开。它没有用户界面。

我在https://developers.google.com/apps-script/class_spreadsheetapp?hl=es-ES#openById找到了这条评论:

// The code below opens a spreadsheet using it's ID and gets the name for it.
// Note that the spreadsheet is NOT physically opened on the client side.
// It is opened on the server only (for modification by the script).
var ss = SpreadsheetApp.openById("abc1234567");

一些示例假设您的脚本正在运行到您的电子表格中。这不是您的情况,因为您将脚本作为服务运行,它应该有自己的用户界面。

于 2012-07-30T20:46:19.050 回答
7

我认为@megabyte1024 解决了语法错误,但在回答您对@YoArgentina 的评论时:

您是否碰巧知道如何通过不在电子表格内运行的服务访问不同选项卡上的数据?

这种有帮助吗?

var ss = SpreadsheetApp.openById(SPREADSHEET_ID_GOES_HERE);
var sheets = ss.getSheets();
// the variable sheets is an array of Sheet objects
var sheet1A1 = sheets[0].getRange('A1').getValue();
var sheet2A1 = sheets[1].getRange('A1').getValue();
于 2012-07-30T22:16:07.713 回答
2

您需要分别访问每个工作表。

var ss = SpreadsheetApp.openById(SPREADSHEET_ID_GOES_HERE);
var sheet = ss.getSheets()[0]; // "access data on different tabs"
ss.setActiveSheet(sheet);
于 2012-07-30T22:10:33.033 回答
1

这两行至少有一个问题。第一个是setActiveSheet方法参数是一个Sheet类对象,getSheetId方法返回一个整数值。顺便说一下,这种方法 (getSheetId)没有记录。如果 SpreadsheetApp 没有活动的电子表格,则可能会发生第二个问题。在这种情况下,有“请先选择一个活动的电子表格”。错误。使用SpreadsheetApp.setActiveSpreadsheet方法设置活动电子表格。

于 2012-07-30T20:52:59.573 回答