見出し画像

[GAS]Googleドライブのフォルダ内の全てのファイルをスプレッドシートに書き出す

Googleドライブのフォルダ内にある全てのファイルをスプレッドシートに一覧として書き出したい、ということはよくあります。

今回は「ファイル名」「最終更新日時」「URL」の3情報を
Google Apps Scriptを用いてスプレッドシートに出力します。

(今回は前提として「フォルダ内にはファイルのみで、フォルダはない」とします)

スクリプトはこちら。

function getFiles01() {

  const targetFolderId = "***Folder_ID***";//対象とするGoogleDriveフォルダID
  const targetFolder   = DriveApp.getFolderById(targetFolderId);

 //別の関数にてフォルダ内のすべてのファイルIDを配列で取得
  const allFilesId = getAllFilesId_(targetFolder);

  const records = [];

  for (const id of allFilesId) {
    
    const file       = DriveApp.getFileById(id);
    const fileName   = file.getName();
    const lastUpdate = file.getLastUpdated();
    const fileUrl    = file.getUrl();

    records.push([fileName, lastUpdate, fileUrl]);

  }

  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(2, 1, records.length, records[0].length).setValues(records);

}

//フォルダ内のすべてのファイルIDを配列にして返す
function getAllFilesId_(targetFolder) {

  const filesIdList = [];

  let files = targetFolder.getFiles();
  while (files.hasNext()) {
    filesIdList.push(files.next().getId());
  }
  return filesIdList;
}

結果、以下のように「ファイル名」「最終更新日時」「URL」の一覧が返されました。


応用として、列A「ファイル名」にハイパーリンクを埋め込むパターンを記します。

スクリプトはこちら。(「function getAllFilesId_」は前掲のものと変更なし)

function getFiles01_2() {

  const targetFolderId = "***Folder_ID***";//対象とするGoogleDriveフォルダID
  const targetFolder   = DriveApp.getFolderById(targetFolderId);

 //別の関数にてフォルダ内のすべてのファイルIDを配列で取得
  const allFilesId = getAllFilesId_(targetFolder);

  const records = [];

  for (const id of allFilesId) {
    
    const file       = DriveApp.getFileById(id);
    const fileName   = file.getName();
    const lastUpdate = file.getLastUpdated();
    const fileUrl    = file.getUrl();
    const hlink    = `=HYPERLINK("${fileUrl}","${fileName}")`

    records.push([hlink, lastUpdate]);

  }

  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(2, 1, records.length, records[0].length).setValues(records);

}

//フォルダ内のすべてのファイルIDを配列にして返す
function getAllFilesId_(targetFolder) {

  const filesIdList = [];

  let files = targetFolder.getFiles();
  while (files.hasNext()) {
    filesIdList.push(files.next().getId());
  }
  return filesIdList;
}

以下のように、ハイパーリンクが埋め込まれたファイル名の列が出来ました。

※続きの記事を書きました。


この記事が気に入ったらサポートをしてみませんか?