从网址Google表格获取文件名

时间:2018-07-18 06:43:23

标签: excel google-apps-script google-sheets

我有问题。 如何从网址获取文件名? enter image description here

enter image description here

3 个答案:

答案 0 :(得分:0)

由于您没有向我们展示您尝试过的内容,所以我通常不会这样做,但是我感到很慷慨。

此功能将为您工作。 (请注意,您需要授予运行权限。)

function getFileNames() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("Get_File_Name");
  var links = sheet.getRange("A2:A").getValues();
  var filenames = []; 
  for (var i = 0; i < links.length; i++) {
    var url = links[i][0];
    if (url != "") {
      var filename = SpreadsheetApp.openByUrl(links[i][0]).getName();
      filenames.push([filename]);
    }
  }
  var startRow = 2; // print in row 2 since row 1 is the header row
  var fileNameColumn = 2; // Column B = column 2
  var destination = sheet.getRange(startRow, fileNameColumn, filenames.length, filenames[0].length);
  destination.setValues(filenames);
}

答案 1 :(得分:0)

另一种方式

function getFileNames() {
  var driveApp = DriveApp;
  // SET THE SHEET HERE
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
  //SET THE URL LINK COLUMN HERE : From row 2 since row 1 is the header row till last row
  var links = sheet.getRange("P2:P").getValues();

  var filenames = []; 

  for (var i = 0; i < links.length; i++) {
    var fileId = getIdFromUrl(links[i][0]);
    if (fileId != "" && fileId != null) {
      var getfile = DriveApp.getFileById(fileId);
      var filename = getfile.getName();
      Logger.log(filename);
      filenames.push([filename]);
    } else {
      filenames.push([""]); 
    }
  }

  // SET STARTING ROW TO PRINT: From row 2 since row 1 is the header row
  var startRow = 2; 
  // SET WHICH COLUMN TO PRINT : Column A = column 1 / Column B = column 2
  // MAKE SURE THE SHEET LAST COLUMN HEADER IS FILLED + 1 (next column)
  var fileNameColumn = sheet.getLastColumn() + 1;  
  var destination = sheet.getRange(startRow, fileNameColumn, filenames.length, filenames[0].length);
  destination.setValues(filenames);
}

function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); }

答案 2 :(得分:-1)

您可以像这样在电子表格中创建自定义功能。

function getSSName(name) {
  var ss = SpreadsheetApp.openByUrl(url);
  return ss.getName();
}