【问题标题】:Checking if a filename exists and updating the file it in Google Script检查文件名是否存在并在 Google Script 中更新文件
【发布时间】:2021-02-16 20:39:36
【问题描述】:

我目前有一个脚本,可以将 Google Sheet 中的数据合并到 Google Doc 模板中。对于工作表的每一行,使用该行中的标题数据创建一个新文档。该脚本工作正常,但不是我的工作。它已传给我,但我对 Google Script 的熟练程度不足以弄清楚我想要实现的目标。

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

脚本如下

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());

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

【问题讨论】:

  • 在谷歌驱动器中可能有相同的文件名
  • 我明白了,那么在这种情况下,是否无法检查可能已经创建的同名文件?

标签: google-apps-script google-sheets google-docs mailmerge


【解决方案1】:

您可以考虑使用searchFiles(params) 根据search query term guidelines 在您的驱动器中搜索具有Doc 类型的特定文件名。找到所有文件名相同的文件后,您可以使用 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());

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

其他参考:

【讨论】:

  • 非常感谢 Ron 抽出宝贵时间撰写深入的答案。对此,我真的非常感激。我想我的第一个后续问题是在哪里将这样的代码集成到我已有的代码中?
  • 根据我对您的代码的理解,我同意您最初认为应该放置的位置。检查应该在创建新文件之前完成let newDoc = DriveApp.getFileById(templateID).makeCopy(fileName);
  • 我也试过修改你的代码。请参考第一个示例代码。
  • 啊,是的,我现在明白了。我将不得不试一试,看看它对我有用。我想我会不加修改地运行脚本来为每一行创建初始文档。从那时起,我将添加这个新脚本,如果它有效,则应该只覆盖现有文档。
  • 是的,如果您遇到一些问题,请告诉我
猜你喜欢
  • 2012-04-18
  • 1970-01-01
  • 2013-08-14
  • 2020-07-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
相关资源
最近更新 更多