24

When you enter an importrange function manually into a spreadsheet you receive a pop up and must 'allow access'.Pop up to allow access for importrange

However, I'm trying to find a way to do this via a script because I'm creating many spreadsheets, each with a query-importrange function (I 'own' the spreadsheet which has data to import). There's too many for me to manually 'allow access' via the pop up and update the function to include the query function.

Hence, I'm looking for a function call in apps script that can perform the same action that the pop up did. Code segment example below.

Does anyone know of a function that can 'allow access'? Stefan

// create new spreadsheet file
...
var ss = createSpreadsheet(fileName);
var spreadsheet = SpreadsheetApp.open(ss);
var sheet = spreadsheet.getSheetByName("Sheet1");

// Add student as Viewer
spreadsheet.addViewer(studentEmail);

// Add ImportRange function 
var sheet = spreadsheet.getSheets()[0];
var cell = sheet.getRange("A1");
var filter = "select * where Col3='" + studentEmail + "'";
var qry = '=QUERY(importRange("' + fileKey + '","14-15S2!A1:AE");"' + filter + '";1)';
cell.setValue(qry);
// I need a function to 'allow access' here, so the function can be allowed access. Otherwise, it throws an error.
...
0

5 Answers 5

15

@Franzi suggested using undocumented approach which works and does not require making a donor/source spreadsheet public. Here's how you can do it from Google App Script:

function addImportrangePermission() {
  // id of the spreadsheet to add permission to import
  const ssId = SpreadsheetApp.getActiveSpreadsheet().getId();

  // donor or source spreadsheet id, you should get it somewhere
  const donorId = '1GrELZHlEKu_QbBVqv...';

  // adding permission by fetching this url
  const url = `https://docs.google.com/spreadsheets/d/${ssId}/externaldata/addimportrangepermissions?donorDocId=${donorId}`;

  const token = ScriptApp.getOAuthToken();

  const params = {
    method: 'post',
    headers: {
      Authorization: 'Bearer ' + token,
    },
    muteHttpExceptions: true
  };
  
  UrlFetchApp.fetch(url, params);
}

Usually there is no need, but in some rare cases you might want to add the required oauthScopes in appscript.json manifest:

  ...,
  "oauthScopes": [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/script.external_request"
  ],
  ...
1
  • 1
    @yago if you want to see the result immediately you'll need to refresh your receiver spreadsheet after fetching the link. Or remove the formula and set it in the cell again. That is a bit inconvenient.
    – kishkin
    Aug 24, 2021 at 14:49
10

I had a problem similar to this and found the answer was to alter the permissions of the spreadhseet file from which you are importing data (the "filekey" in your example").

This is the google app script that made "Allow Access" go away for me:

file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW)
3
  • 1
    This is the only solution - imported sheet must by public and you don't have Allow access anymore. Thanks.
    – s3m3n
    Jul 8, 2016 at 11:48
  • 2
    Be aware that file.setSharing(DriveApp.Access.DOMAIN_WITH_LINK, DriveApp.Permission.VIEW); or file.setSharing(DriveApp.Access.DOMAIN_WITH_LINK, DriveApp.Permission.EDIT); does NOT work. Apr 23, 2019 at 20:27
  • 1
    Below answers are now up to date with valid solutions--answer from @Max Makhrov looks best to me
    – Lle.4
    Feb 2, 2022 at 19:55
9

I'm doing it automatically using the gspread python library by calling the addimportrangepermissions endpoint.

    sheet.client.request(
        'post',
        f'https://docs.google.com/spreadsheets/d/{sheet.spreadsheet.id}/externaldata/addimportrangepermissions',
        params={'donorDocId': external_sheet.spreadsheet.id}
    )

I know it's not via the apps script, but it could provide you some hints on how to do it there.

Note: I didn't find any doc about this, so I though this could help anyone trying to do the same in any platform (app script, python, etc.).

2

This code is based on the answer by @kishkin:

/**
 * https://stackoverflow.com/questions/28038768
 * @param {string} fileId - id of the spreadsheet to add permission to import
 * @param {string} donorId - donor or source spreadsheet id, you should get it somewhere
 */
function addImportrangePermission_(fileId, donorId) {
  // adding permission by fetching this url
  var url = 'https://docs.google.com/spreadsheets/d/' +
    fileId +
    '/externaldata/addimportrangepermissions?donorDocId=' +
    donorId;
  var token = ScriptApp.getOAuthToken();
  var params = {
    method: 'post',
    headers: {
      Authorization: 'Bearer ' + token,
    },
    muteHttpExceptions: true
  };
  UrlFetchApp.fetch(url, params);
}

It is compatible with the ES5 engine and easily used as a function outside.

3
  • Is this viewable anywhere in the API docs? And, just to be clear, this just uses internal Google services, right? Not referencing an external service?
    – Lle.4
    Jan 28, 2022 at 2:29
  • Don't know, it's from answer by @Franzi Jan 31, 2022 at 8:33
  • So @Max Makhrov, where do I put this function? How/when is it executed? 4 hours ago
1

All I did was share the 'source' sheets - the sheets from which ImportRange grabs its data - with the people in my organsation who are using the gsheet template. I edited the template by clicking the authorise access button and all sheets that I have made from the template since have worked.

The ImportRange function works without me having to re-authorise access within each new sheet created from the template. I hope it works for others in my organisation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.