检查文件名是否存在并在Google脚本中更新文件 [英] Checking if a filename exists and updating the file it in Google Script

查看:57
本文介绍了检查文件名是否存在并在Google脚本中更新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个脚本,可将Google表格中的数据合并到Google Doc模板中.对于工作表的每一行,使用该行中的标题数据创建一个新文档.该脚本工作正常,但不是我的工作.它已经传给我了,我对Google Script的掌握还不够熟练,无法弄清楚我想要实现的目标.

I currently have a script which merges data from a Google Sheet into a Google Doc template. For each row of the worksheet, a new document is created using the title data from the row. The script works fine, but isn't my work. It has been passed onto me and I'm not skilled enough at Google Script to figure out what I'd like to achieve.

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

Ideally I wanted to know if it was possible to check when the script is run whether the document file already exists. It would do this as each document that is created uses the title data from the worksheet. If the document does exist then the data could be updated in that sheet, rather than creating a new version of it.

脚本如下

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

};

是否有可能在这些方面附近建立某种条件?

Would it be possible to set up some kind of conditional, perhaps around these lines?

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

updateFileData(row, newDoc.getId());

我希望有人可以以此指向我正确的方向.任何建议都将不胜感激.

I'm hoping someone can point me in the right direction with this. Any advice is much appreciated.

推荐答案

您可以考虑使用 searchFiles(params)可根据 setTrashed(trashed),然后使用模板文档创建新文件

You can consider using 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) before creating a new file using the template document

示例代码:

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

  };

  • 在此给定的示例代码中,我们将循环所有具有确切文件名的文件,并在创建新文件之前删除每个文件.
  • 其他参考:

    这篇关于检查文件名是否存在并在Google脚本中更新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆