Get Google Sheet by ID?

2020-02-23 05:50发布

I know that Google Apps Script has a getSheetId() method for the Sheet Class, but is there any way to select a sheet within a spreadsheet by referencing the ID?

I don't see anything like getSheetById() in the Spreadsheet Class documentation.

5条回答
手持菜刀,她持情操
2楼-- · 2020-02-23 06:24

You can use something like this :

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

var sheet = getSheetById(123456789);

And then to find the sheet ID to use for the active sheet, run this and check the Logs or use the debugger.

function getActiveSheetId(){
  var id  = SpreadsheetApp.getActiveSheet().getSheetId();
  Logger.log(id.toString());
  return id;
}
查看更多
疯言疯语
3楼-- · 2020-02-23 06:27

Look at your URL for query parameter #gid

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

In example above gid=910184575, so you can do something like this:

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;
    }
  }
}
查看更多
狗以群分
4楼-- · 2020-02-23 06:34

Try openById(id) as outlined in in Google's documentation:

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

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

查看更多
smile是对你的礼貌
5楼-- · 2020-02-23 06:35
var sheetActive = SpreadsheetApp.openById("ID");
var sheet = sheetActive.getSheetByName("Name");
查看更多
SAY GOODBYE
6楼-- · 2020-02-23 06:39

Not sure about ID but you can set by sheet name:

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

The SpreadsheetApp Class has a setActiveSheet method and getSheetByName method.

查看更多
登录 后发表回答