如果Google Drive文件夹中已经存在相同名称的文件,则附加代码以覆盖PDF

问题描述 投票:0回答:1

我有此脚本可将电子表格保存在Google云端硬盘Squads文件夹中。

[保存文件的名称是根据H2页面的单元格Gerais中的值,有时会重复该名称,并且在保存时会创建一个新文件,而不是订阅现有文件,希望在此代码中添加以下选项:如果已经存在与该新文件同名的文件,而不是在Google Drive Squads文件夹中有两个同名文件,则旧文件将完全消失,并且仅新文件可用

    //Create PDF
    SpreadsheetApp.flush();

    var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/' + // Best to place the line break after '+'
      'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +  // SHEET ID
        '/export?format=pdf' +
          '&size=0' +
            '&portrait=true' +
              '&fitw=true' + 
                '&top_margin=0' +            
                  '&bottom_margin=0' +         
                    '&left_margin=0' +        
                      '&right_margin=0' +     
                        '&sheetnames=false&printtitle=false' +
                          '&pagenum=false' +
                            '&gridlines=false' +
                              '&fzr=FALSE' +
                                '&gid=' +
                                  'XXXXXXXXXXXX'; //SHEET PAGE ID

    var token = ScriptApp.getOAuthToken();
    var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' +  token } });
    var pdfBlob = docurl.getBlob();

    // Get filename from sheet "Gerais", cell "H2"
    var fileName = spreadsheet.getSheetByName("Gerais").getRange("H2").getValue();

    // Create file from blob and name it
    // The newFile is placed in the root folder by default
    var newFile = DriveApp.createFile(pdfBlob).setName(fileName);  

    // if folder exists use next 
    if (DriveApp.getFoldersByName("Squads").hasNext()){
      var folder = DriveApp.getFoldersByName("Squads").next();

      // if folder does not exist
    } else {
      var folder = DriveApp.createFolder("Squads");// new folder created in the root folder by default
    }

    folder.addFile(newFile); // add new file to folder
    DriveApp.removeFile(newFile); // remove file from root folder

我也尝试在IFELSE之间创建交互,以使文件名与文件夹名相同,但尝试失败)>

我有此脚本将电子表格保存在Google Drive Squads文件夹中。已保存文件的名称取决于Gerais页面H2单元格中的值,有时会重复出现该名称...]]

问题

用名称覆盖File中现有的Folder(可能是唯一的)。

解决

如何检查是否存在一个名称写在fileName变量中的文件,如果存在,在添加新创建的文件之前将其删除? 修改

看起来像这样(您的脚本已被scopes required for the API之一授权):
//prepare new file and Squads folder;

var existing = folder.getFilesByName(fileName); //returns file iterator;
var hasFile = existing.hasNext(); //check if iterator isn't empty;
if(hasFile) {
  var duplicate = existing.next(); //access file;

  //delete file;
  var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
  var dres = UrlFetchApp.fetch(durl,{
    method: 'delete',
    muteHttpExceptions: true,
    headers: {'Authorization': 'Bearer '+token}
  });
  if(dres.getResponseCode()>=400) {
    //handle errors;
  }
}

//continue: add file, remove from root, etc;

注释

  1. 定义查询参数的方式是pyramid of doom的常见情况。此外,每个参数都是硬编码的,这使得导出变得不灵活。为了避免这种情况,请使用对象进行配置(因为查询不过是一组键值对):

var params = {
  format: 'pdf',
  size: 0,
  portrait: true,
  fitw: true,
  top_margin: 0,        
  bottom_margin: 0,        
  left_margin: 0,    
  right_margin: 0,   
  sheetnames: false,
  printtitle: false,
  pagenum: false,
  gridlines: false,
  fzr: 'FALSE',
  gid: 'XXXXXXXXXXXX'
};

//append params to the url;
var theurl = 'base?'+Object.keys(params).map(function(key){
  return key+'='+params[key];
}).join('&');

更新

更正为UrlFetchApp.fetch()method调用应该是参数对象属性,而不是参数。

参考

  1. Drive APIdeletereference;
pdf google-apps-script google-sheets google-drive-api
1个回答
0
投票

问题

© www.soinside.com 2019 - 2024. All rights reserved.