按名称而不是ID获取Google Spreadsheet

时间:2019-02-04 15:48:42

标签: google-apps-script google-sheets google-drive-api

我正在尝试从另一个电子表格导入数据,并在下面找到了工作代码。如何通过名称而不是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);

}

1 个答案:

答案 0 :(得分: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中)并从那里获取是更合理的选择。因此,您每月只需使用installable trigger运行一次getSpreadsheet