检查文件名是否存在并在 Google 脚本中更新文件

Checking if a filename exists and updating the file it in Google Script

我目前有一个脚本可以将 Google Sheet 中的数据合并到 Google 文档模板中。对于作品的每一行sheet,都会使用该行的标题数据创建一个新文档。该脚本工作正常,但不是我的作品。它已经传给我了,我对 Google 脚本的熟练程度不够高,无法弄清楚我想要实现什么。

理想情况下,我想知道是否可以检查脚本何时 运行 文档文件是否已经存在。它会这样做,因为创建的每个文档都使用作品 sheet 中的标题数据。如果文档确实存在,则可以在 sheet 中更新数据,而不是创建它的新版本。

脚本如下

function mergeDocSheet() {
  const TEMPLATE_ID = '16YfyeDjGDp-88McAtLCQQyZ1xz4QX5z';// Google Doc template ID
  const SS_ID = '1C5gtJCSzHMuSz-oVWEItl2EUVRDwF5iH_'; // Google Sheet ID
  const SHEET_NAME = "data"; // Google Sheet Tab name
  const MAPPED = mappedDocToSheet; 
  const FILE_NAME = ["Titre de la formation"] // Header IDs from sheet.

  docMerge(TEMPLATE_ID,SS_ID,SHEET_NAME,MAPPED, FILE_NAME);

}

function docMerge(templateID,ssID, sheetName, mapped, fileNameData, rowLen = "auto"){
  //Get the Spreadsheet and sheet tab
  const ss = SpreadsheetApp.openById(ssID);
  const sheet = ss.getSheetByName(sheetName);

  //Get number of rows to process
  rowLen = (rowLen = "auto") ? getRowLen() - 1 : rowLen;

  //Gets the range of data in the sheet then grabs the values of the range
  const range = sheet.getRange(1,1,rowLen,sheet.getDataRange().getNumColumns());
  const matrix = range.getValues();

  // Searches the file mapped object and finds the corresponding number returns the column number in an array.
  const fileNameRows = getFileNameRows()


  //Loops through each row of the sheet grabbing the data from each row and putting it into a new doc.
  for(let i = 1; i < rowLen; i++){
    let row = matrix[i];
    //Get the title for the file.
    let fileName = buildFileName(row)

    let newDoc = DriveApp.getFileById(templateID).makeCopy(fileName);

    updateFileData(row, newDoc.getId());

  }; 

  function updateFileData(rowArray, doc){

    //Loops through the mapped object. 
    mapped.forEach(function(element){

      let textID = `\{\{${element.doc}\}\}`
 
      DocumentApp.openById(doc).getBody().replaceText(textID,
                                 rowArray[element.col]);
   });
  };

  function buildFileName(rowArry){

   let fileNameArray = fileNameRows.map(ele => rowArry[ele]);

   return fileNameArray.join("_");
  };


  function getFileNameRows(){
  //Map the column indexes from fileNameData
    let fileNameLocs = fileNameData
                      .flatMap(name => {
                        return mapped.filter(element => element.sheet === name)
                      .map(ele => ele.col);
  });

    return fileNameLocs;
  };

  function getRowLen(){
   return sheet.getDataRange().getNumRows();
  };

};

是否可以围绕这些行设置某种条件?

let newDoc = DriveApp.getFileById(templateID).makeCopy(fileName);

updateFileData(row, newDoc.getId());

我希望有人能为此指出正确的方向。非常感谢任何建议。

在使用模板文档创建新文件之前,您可以考虑使用searchFiles(params) to search for a specific filename with Doc type in your drive based on the search query term guidelines. Once you found all the files having the same filename, you can delete each file using setTrashed(trashed)

示例代码:

  //Loops through each row of the sheet grabbing the data from each row and putting it into a new doc.
  for(let i = 1; i < rowLen; i++){
    let row = matrix[i];
    //Get the title for the file.
    let fileName = buildFileName(row);

    //This query parameter will search for an exact match of the filename with Doc file type
    let params = "title='"+fileName+"' and mimeType = 'application/vnd.google-apps.document'"
    let files = DriveApp.searchFiles(params);
    while (files.hasNext()) {
      //Filename exist
      var file = files.next();
      ///Delete file
      file.setTrashed(true);
    }
    
    //Create a new file
    let newDoc = DriveApp.getFileById(templateID).makeCopy(fileName);
    
    updateFileData(row, newDoc.getId());

  };
  • 在这个给定的示例代码中,我们将循环所有具有确切文件名的文件并在创建新文件之前删除每个文件。

其他参考文献: