見出し画像

【GAS】Google Apps Script 活用事例 当月のドキュメントを複製して、翌月分として保存するスクリプト

当月分のドキュメントを複製、リネーム、内容(試用期間)など一部を書き換えるスクリプトです。

完成したスクリプトはこんな感じ

/**
 * シート全体から一部の列かつ、ステータス列がactiveの部分のみ2次元配列で取得する
 * 
 *  return {object} 2次元配列
 *
 */
function getSheetValues_() {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheet       = spreadsheet.getSheetByName('DB');
  const values      = sheet.getDataRange().getDisplayValues();

  //ヘッダー行の設定
  const header = values[0];
  const column = {
    name:       header.indexOf('求人名'),
    leader:     header.indexOf('責任者'),
    url:        header.indexOf('求人ページURL'),
    status:     header.indexOf('ステータス')
  } 

  //console.log(values);

  const keys    = Object.keys(column);
  const numbers = keys.map(key => column[key]);
  console.log(numbers);
   
   //2次元配列から必要な列のみ取得する
  const newValues = values.map(array => array.reduce((accumulator, current, index) =>{
      if(numbers.includes(index)){
        accumulator.push(current);
      }
    return accumulator
    }, [])//reduce
  );//map
   

   //activeのみ取得する
  const filtered = newValues.filter(row => row.indexOf('active')!== -1)
  console.log(filtered);
  console.log(`配列の要素数: ${filtered.length}`);

  return filtered

}


/**
 *  [['5月度求人票', '野比のび太', 'https://*****.com', 'active']]
 *  配列の2番目に求人票のURLが含まれている
 * 
 */
function makeCopyDocument(){
  const values = getSheetValues_();

  //2次元配列から求人票のURLのみ取得し、1次元配列にする
  //GoogleドキュメントのURLからファイルIDを取得する
  const array  = values.map(row => row[2]
  .replace('https://docs.google.com/document/d/', '')
  .replace('/edit', ''));

  console.log(array);

  for(let i = 0; i < array.length; i++){
    //5月分のファイルを複製し、6月分として保存している
    openDocument_(array[i]);
  }
}


/**
 *  5月の求人票 (ドキュメント) を開いて複製、試用期間のみを書き換えする
 * 
 */
function openDocument_(originalId){
  const sourceDocument = DriveApp.getFileById(originalId);
  const originalName   = sourceDocument.getName();

  //ファイル名をシートの情報で置き換える
  const fileName = originalName
  const newName  = fileName.replace('5月入社', '6月入社');

  //console.log('リネーム前:', fileName);
  console.log('リネーム後:', newName);

  const folder = DriveApp.getFolderById('***********');
  const duplicatedDocument = sourceDocument.makeCopy(fileName, folder);
  const fileId = duplicatedDocument.getId();

  //複製したドキュメントを開いて試用期間のみを書き換える
   const document = DocumentApp.openById(fileId);
  document.getBody()
  .replaceText('2022年3月1日~5月31日','2022年6月1日~8月31日');

  document.setName(newName);

  return
}


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