LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Monday, August 15, 2022

Google Driveで特定フォルダ内にあるファイルの説明をDocumentに書き出したい


Google Driveの特定フォルダ内にあるファイルの説明をすべて取得してドキュメントに書き出したくて書いたコードです。

書き出す順番はファイル名を昇順で並べ替えています。

実行プロセスの概要
  1. getFileDescriptionsInFolder() :フォルダを指定してファイルをすべて取得します
  2. fileObjArray.sort(asc):ファイル名の昇順で並べ替えます
  3. createDescriptionArray(sortedArray) :説明だけの配列を作ります
  4. descriptionsArray.join("\n") :配列を改行でつなげた文字列にします
  5. addTextToDocument(str) :指定したDocumentに書き出します



コード.gs
function addFileDescriptionsToDocument() {
  const fileObjArray = getFileDescriptionsInFolder();
  const sortedArray = fileObjArray.sort(asc);
  Logger.log(sortedArray);
  const descriptionsArray = createDescriptionArray(sortedArray);
  const str = descriptionsArray.join("\n");
  addTextToDocument(str);
}

function getFileDescriptionsInFolder() {
  const folderId = "FOLDER_ID";
  const folder = DriveApp.getFolderById(folderId);
  const files = folder.getFiles();
  let array = [];
  while(files.hasNext()) {
    const file = files.next();
    const obj = {};
    obj["name"] = file.getName();
    obj["url"] = file.getUrl();
    obj["description"] = file.getDescription();
    array.push(obj);
  }
  return array;
}

function asc(a, b){
  const targetA = a.name;
  const targetB = b.name;
  if(targetA > targetB){
    return 1;
  }else if(targetA < targetB ){
    return -1;
  }else{
   return 0;
  }
}

function createDescriptionArray(sortedArray) {
  const array = [];
  const target = "description";
  for(let i = 0; i < sortedArray.length; i++){
    const description = sortedArray[i][target];
    array.push(description);
  }
  return array;
}

function addTextToDocument(description) {
  const url = "DOCUMENT_URL";
  const doc = DocumentApp.openByUrl(url);
  const body = doc.getBody();
  body.appendParagraph(description);
}



参考

Google Driveのファイルの説明をフォルダ単位で取得したい

Latest post

スプレッドシートA列にある複数のテキストをスライドに追加したい(Google Apps Script)

今回Google Apps Scriptでやりたいこと GoogleスプレッドシートA列にある複数の値を取得して Googleスライドに渡して 図形オブジェクトのテキストとして追加したい ① スプレッドシートのA列に値を入れておく ② Code.gsのinsertNewShape...