如何通过Google Apps脚本访问不同Google电子表格中的数据?

Mat*_*are 10 google-apps-script

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

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

function doGet(e) {

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

    //....
}
Run Code Online (Sandbox Code Playgroud)

我收到了错误

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

我将此工作从此链接中删除:在Google Spreadsheets中存储数据以及在构建用户界面下列出的Ui服务部分.

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

Ale*_*tri 22

setActiveSheet只能与UI显示的电子表格一起使用,您可以在浏览器中打开的电子表格中使用该表格.

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

我在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");
Run Code Online (Sandbox Code Playgroud)

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

  • 只需使用getSheetByName('工作表的名称'),默认情况下为'Sheet1',除非您对其进行了重命名,或者如果您未使用英语...例如法语,则默认值为'Feuille1' (2认同)

Ada*_*amL 5

我认为@ 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();
Run Code Online (Sandbox Code Playgroud)

  • 你确定你没有使用`var doc = SpreadsheetApp.openById(SPREADSHEET_ID_GOES_HERE).getActiveSheet();`在原帖中?使用这篇文章中的代码,`ss`应该是一个Spreadsheet对象,而不是Sheet对象. (3认同)