how to programmatically open a new spread sheet from google scripts

三世轮回 提交于 2019-12-08 07:07:15

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/37616007/how-to-programmatically-open-a-new-spread-sheet-from-google-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!