按名称,而不是ID获取谷歌电子表格

问题描述 投票:0回答:1

我试图从另一个电子表格中导入数据,发现下面的工作代码。如何通过名字而不是ID的文件?

(该文件ID每月变化,但文件名称将保持不变。)

function ImportRange() {


var values = SpreadsheetApp.openById('xxxxxx').
  getSheetByName(‘xxx').getRange('A1:D100').getValues();
 SpreadsheetApp.getActiveSheet()
                .getRange( 1, 1, values.length, values[0].length )
                .setValues(values);

}
google-apps-script google-sheets google-drive-sdk
1个回答
0
投票

你可以用迭代经过与DriveApp电子表格,让他们所有,然后按名称对它们进行比较:

/* 
The function will iterate through spreadsheets in a given folder and return DriveApp file object (https://developers.google.com/apps-script/reference/drive/file)
folderId — string — the id of the folder to search for the target spreadsheet; root folder will be used if nothing is passed
targetSpreadsheetName - string - the name of the spreadsheet to be found
*/
function getSpreadsheet(folderId, targetSpreadsheetName) {
  var folder = folderId ? DriveApp.getFolderById(folderId) : DriveApp.getRootFolder();
  var spreadsheets = folder.getFilesByType(MimeType.GOOGLE_SHEETS);
  while (spreadsheets.hasNext()) {
    var spreadsheet = spreadsheets.next();
    if (spreadsheet.getName() === targetSpreadsheetName) {
      return spreadsheet.getId();
    }
  }
  return null;
}

然后在你的ImportRange功能,你会使用这种方式:

function ImportRange() {
var id = getSpreadsheet('', 'Untitled spreadsheet'); //this way you'd get a spreadsheet named 'Untitled spreadsheet' in your root folder
if (id === null) return 'No spreadsheet';
var values = SpreadsheetApp.openById(id). 
  getSheetByName('xxx').getRange('A1:D100').getValues();
 SpreadsheetApp.getActiveSheet()
                .getRange( 1, 1, values.length, values[0].length )
                .setValues(values);

}

这个功能似乎相当慢,虽然(它拿着剧本四处1秒遍历在我的案件超过1表格),我不建议你每次运行Import range时间运行它。如果你的目标表格的ID每月的变化,它会更合理地存储在某个地方 - 在技术电子表格或document/script properties - 并从那里得到它。因此,你需要每月只有一次与getSpreadsheet运行installable trigger

© www.soinside.com 2019 - 2024. All rights reserved.