how to programmatically open a new spread sheet fr

2019-06-07 07:35发布

in setActiveSpreadSheet doc the example is very clear:

// The code below will make the spreadsheet with key "1234567890" the active spreadsheet
var ss = SpreadsheetApp.openById("1234567890");
SpreadsheetApp.setActiveSpreadsheet(ss);

however implementing that inside my google scripts, nothing happens at all (not even an error message).. ideas?

update

Based on the answers below, it's clear that the above code has no effect on UI. I tried doing this:

function goToEstimate(sheetId)
{
  window.open('https://docs.google.com/spreadsheets/d/'+sheetId);
}

but then I got this error:

ReferenceError: "window" is not defined.

Is there a way to access the javascript global window variable from within google scripts?

2条回答
贼婆χ
2楼-- · 2019-06-07 08:18

An Apps Script cannot make a spreadsheet appear in a client's browser, since it is a server side script.

The method openById returns a handle on a spreadsheet which makes it possible to manipulate with the spreadsheet from the Apps Script. This is what "to open a spreadsheet" means for a script. This action has no effect on user's interface.

The method setActiveSpreadsheet is pretty much useless; it only changes which spreadsheet will be returned when a script calls getActiveSpreadsheet.

One method that does have effect on UI is setActiveSheet: if it is applied to a spreadsheet that a user has opened in their browser, the method can change which tab/sheet of that spreadsheet is facing the user.

查看更多
倾城 Initia
3楼-- · 2019-06-07 08:33

I guess, you can't just open new tab in browser and open new spreadsheet by script. That's because script can't control browsers. But you could get data from closed Spreadsheet:

function openSheetTest() {
  var newWs = SpreadsheetApp.openById('1234567890');
  var sheet = newWs.getSheetByName('Sheet1');

  var data = sheet.getDataRange().getValues();

  Logger.log(data);
}

There's is a class Browser in G-sheets. And all we can for now is to make promts or MsgBoxes.

查看更多
登录 后发表回答