2012-07-30 63 views
9

我正在Google網站上撰寫Google Apps腳本,並試圖使用Google電子表格中2個不同選項卡上提供的數據。從我認爲我從文檔中瞭解到的情況,我可以使用openById()方法在Sites腳本中使用SpreadsheetApp類中的所有可用方法。如何通過Google Apps腳本訪問不同Google電子表格上的數據?

反正這裏是我試圖做

function doGet(e) { 

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

    //.... 
} 

我得到的錯誤

Cannot find method setActiveSheet(. (line 4)

我拉我的工作,關閉此鏈接:Storing Data in Google Spreadsheets也UI服務部大樓下上市用戶界面。

有人看到我在這兩行中做錯了嗎?

+1

我建議你應該使用腳本編輯器的自動完成功能,以避免語法錯誤或使用不適用的方法......這是一個開始,沒有惱人的錯誤和/或錯別字一個簡單的方法;-) – 2012-07-30 22:53:57

回答

18

setActiveSheet只能用於用戶界面顯示的電子表格,這是您在瀏覽器中打開的電子表格中的工作表。

使用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"); 

一些例子假設你的腳本運行到您的電子表格。這不是你的情況,因爲你正在運行腳本作爲服務,它應該有它自己的用戶界面。

+1

這有點令人失望。您是否碰巧知道在不同選項卡上訪問數據的方式,然後通過未在電子表格中運行的服務? – Mathitis2Software 2012-07-30 21:12:38

+1

只需使用getSheetByName('工作表的名稱'),默認情況下它是'Sheet1',除非您重命名或者如果您不使用英語...例如法語,默認值爲'Feuille1' – 2012-07-30 22:15:35

+1

getSheets()將爲您帶來一個包含電子表格中所有表單的陣列。 – 2012-07-31 15:16:41

1

這兩行至少有一個問題。第一個是setActiveSheet方法參數是一個Sheet類對象,getSheetId方法返回一個整數值。順便說一下這個方法(getSheetId)是not documented。如果SpreadsheetApp沒有活動的電子表格,則可能會發生第二個問題。在這種情況下,請選擇「請先選擇有效的電子表格」。錯誤。使用SpreadsheetApp.setActiveSpreadsheet方法設置活動電子表格。

0

您需要分別訪問每張紙。

var ss = SpreadsheetApp.openById(SPREADSHEET_ID_GOES_HERE); 
var sheet = ss.getSheets()[0]; // "access data on different tabs" 
ss.setActiveSheet(sheet); 
+1

「你碰巧知道一種方法來訪問不同選項卡上的數據,然後通過未在電子表格中運行的服務?」 var sheet1 = ss.getSheets()[0]; – 2012-07-30 22:12:05

+0

看起來我無法通過獨立服務訪問該方法。好像我必須使用getSheetID(),getSheetName()和getSheetValues() – Mathitis2Software 2012-07-31 01:16:29

4

我覺得@ megabyte1024解決了語法錯誤,但在回答您的評論對@YoArgentina:

Do you happen to know of a way to access data on different tabs then through a service not running inside the Spreadsheet?

這是否有點幫助?

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(); 
+0

看起來像在Spreadsheet腳本的外部無法訪問getSheets()=> TypeError:在對象Sheet中找不到函數getSheets。 (第4行) – Mathitis2Software 2012-07-31 01:18:18

+1

您確定您不是在原始文章中使用'var doc = SpreadsheetApp.openById(SPREADSHEET_ID_GOES_HERE).getActiveSheet();'嗎?用這篇文章中的代碼,'ss'應該是一個Spreadsheet對象,而不是一個Sheet對象。 – AdamL 2012-07-31 01:32:44

+0

是的,你是100%正確的。我完全錯過了。非常感謝。 – Mathitis2Software 2012-07-31 01:54:39

相關問題