通过ID获取Google表格?

时间:2014-10-31 19:41:08

标签: google-apps-script google-sheets

我知道Google Apps脚本的工作表类别有getSheetId() method,但有没有办法通过引用ID来选择电子表格中的工作表?

我在Spreadsheet Class documentation中看不到类似getSheetById()的内容。

6 个答案:

答案 0 :(得分:16)

您可以使用以下内容:

function getSheetById(id) {
  return SpreadsheetApp.getActive().getSheets().filter(
    function(s) {return s.getSheetId() === id;}
  )[0];
}

var sheet = getSheetById(123456789);

然后找到要用于活动工作表的工作表ID,运行它并检查日志或使用调试器。

function getActiveSheetId(){
  var id  = SpreadsheetApp.getActiveSheet().getSheetId();
  Logger.log(id.toString());
  return id;
}

答案 1 :(得分:3)

var sheetActive = SpreadsheetApp.openById("ID");
var sheet = sheetActive.getSheetByName("Name");

答案 2 :(得分:1)

在URL中查询查询参数 #gid

https://docs.google.com/spreadsheets/d/1Vk7kzMD3DhfUeLasDdSK6Z9ScNrryPrawAxHGFimKp8/edit#gid=910184575

在上述 gid = 910184575 的示例中,因此您可以执行以下操作:

function getSheetById_test(){
  var sheet = getSheetById(910184575);
  Logger.log(sheet.getName());
}

function getSheetById(gid){
  for each (var sheet in SpreadsheetApp.getActive().getSheets()) {
    if(sheet.getSheetId()==gid){
      return sheet;
    }
  }
}

答案 3 :(得分:0)

我很惊讶这个 API 不存在......它似乎是必不可少的。无论如何,这就是我在 GAS Utility 库中使用的:

/** 
  * Searches within a given Google Spreadsheet for a provided Sheet ID and returns
  * the Sheet if the sheet exists; otherwise it will return undefined if not found.
  *
  * @param {Spreadsheet} ss - a Google Spreadsheet object (https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet)
  * @param {Integer} sheetId - the ID of a Google Sheet 
  * @return {Sheet} the Google Sheet object if found; otherwise undefined (https://developers.google.com/apps-script/reference/spreadsheet/sheet)
  */
function getSheetById(ss, sheetId) {
  var foundSheets = ss.getSheets().filter(sheet => sheet.getSheetId() === sheetId);
  return foundSheets.length ? foundSheets[0] : undefined;
}

答案 4 :(得分:-1)

按照Google的文档中所述尝试openById(id)

var ss = SpreadsheetApp.openById("sheetID");

参考:https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#openById(String)

答案 5 :(得分:-2)

不确定ID,但您可以按工作表名称设置:

var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("your_sheet_name"));

SpreadsheetApp类有一个setActiveSheet methodgetSheetByName method