LANG SELRCT

Google Apps Scriptのコードを書く場所  (新規作成: スプレッドシート | スクリプトエディタ

2022年8月15日月曜日

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のファイルの説明をフォルダ単位で取得したい

最新の投稿

JIRA APIで選択リスト(複数選択)を課題作成時に選択してPOSTしたい

JIRA APIを利用して選択リスト(複数選択)フィールドに値を入れたくて書いたコードです。 コード.gsのこの部分で複数選択の値を選択できました。 customfield_10043 は手元のJIRAでの選択リスト(複数選択)のフィールドIDなので、各自の環境によって異なります...