【问题标题】:Adding Replace Existing File to GmailToDrive App Script - Follow up Question将替换现有文件添加到 GmailToDrive 应用脚本 - 后续问题
【发布时间】:2020-03-07 13:34:14
【问题描述】:

这是相关帖子的另一个问题:Adding Replace Existing File to GmailToDrive App Script@Tanaike. 回答

我正在尝试将上一篇文章中的代码与带有 xlsx 文件的编辑功能一起使用。一切似乎都工作正常,它抓取文件并保存它,甚至更新了谷歌驱动器文件夹中的修改日期。但是,excel文件的内容与原来的并没有变化。我已启用 Drive API。这与 xlsx 文件类型兼容吗?是否需要额外的东西来实际更新文件中的内容而不仅仅是元数据?

// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['xlsx'];
//Name of the folder in google drive i which files will be put
var folderName = 'YourfolderName;
//Name of the label which will be applied after processing the mail message
var labelName = 'Saved2';


function GmailToDrive(){
  //build query to search emails
  var query = '';
  //filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+formattedDate+
  for(var i in fileTypesToExtract){
 query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  }
  query = 'in:inbox label:MyCustomLabel has:attachment ' + query;
  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  if(threads.length > 0){
    parentFolder = getFolder_(folderName);
  }
  var root = DriveApp.getRootFolder();
  for(var i in threads){
    var mesgs = threads[i].getMessages();
 for(var j in mesgs){
      //get attachments
      var attachments = mesgs[j].getAttachments();
      for(var k in attachments){
        var attachment = attachments[k];
        var isDefinedType = checkIfDefinedType_(attachment);
     if(!isDefinedType) continue;
        var attachmentBlob = attachment.copyBlob();
        var existingFile = DriveApp.getFilesByName(attachment.getName());
        if (existingFile.hasNext()) {
          var file = existingFile.next();
          Drive.Files.update({}, file.getId(), attachmentBlob);
        } else { // Added
          var file = DriveApp.createFile(attachmentBlob); // Added
          parentFolder.addFile(file); // Added
          root.removeFile(file); // Added
        }
      }
 }
 threads[i].addLabel(label);
  }
}

//This function will get the parent folder in Google drive
function getFolder_(folderName){
  var folder;
  var fi = DriveApp.getFoldersByName(folderName);
  if(fi.hasNext()){
    folder = fi.next();
  }
  else{
    folder = DriveApp.createFolder(folderName);
  }
  return folder;
}

//getDate n days back
// n must be integer
function getDateNDaysBack_(n){
  n = parseInt(8);
  var date = new Date();
  date.setDate(date.getDate() - n);
  return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy/MM/dd');
}

function getGmailLabel_(name){
  var label = GmailApp.getUserLabelByName(name);
  if(!label){
 label = GmailApp.createLabel(name);
  }
  return label;
}

//this function will check for filextension type.
// and return boolean
function checkIfDefinedType_(attachment){
  var fileName = attachment.getName();
  var temp = fileName.split('.');
  var fileExtension = temp[temp.length-1].toLowerCase();
  if(fileTypesToExtract.indexOf(fileExtension) !== -1) return true;
  else return false;
}

【问题讨论】:

  • 为了正确理解However, the content of the excel file does not change from the original.,能否将existingFile.hasNext()的值显示为if (existingFile.hasNext()) {
  • 您能多解释一下您的if (existingFile.hasNext()) - else 子句吗?我一直在努力理解它,但我一直无法做到
  • 这部分脚本来自@Tanaike 在上一篇文章中关于如何编辑文件而不是替换的回答。该文件只是一个简单的测试 excel 文件,其中包含几列和几行带有虚拟数据的行。我将文件保存到驱动器,然后发送另一封具有相同文件名和不同数据的电子邮件。该脚本能够找到电子邮件并获取文件。它甚至更新了 google drive 中的修改日期,以反映它刚刚被修改,但文件中的数据仍然是原始数据。

标签: google-apps-script google-drive-api gmail-api


【解决方案1】:

因为 .xlsx 是 Excel 格式,Apps Script 不能修改其内容,因为它不是 Google 产品,这就像尝试使用 Apps Script 修改 pdf ,但不用担心,您可以将 .xlsx 文件转换为原生 Google 电子表格格式,然后像处理普通的 Google 电子表格一样处理它。此函数将为您进行转换:

// this Function will convert your .xlsx files into native Google Spreadsheet format
function convertExceltoGoogleSpreadsheet(parentFolder) {
  var files = parentFolder.getFiles();
  while(files.hasNext()){
    var file = files.next();
    // If the file contains the .xlsx extention in its name
    // then it will return an array with length 2
    var filename = file.getName().split(/.xlsx?/);
    if(filename.length > 1){
      // build info to create the new file with Google Spreadsheet format
      var resource = {
        title: filename[0],
        mimeType: MimeType.GOOGLE_SHEETS,
        parents: [{id: parentFolder.getId()}],
      };
      // Return the response after creating the file 
      return Drive.Files.insert(resource, file.getBlob());
    }   
  }
}

然后,在这部分代码中使用该函数:

...
        var attachmentBlob = attachment.copyBlob();
        var existingFile = DriveApp.getFilesByName(attachment.getName());
        if (existingFile.hasNext()) {
          var file = existingFile.next();
          Drive.Files.update({}, file.getId(), attachmentBlob);
        } else { 
           var file = DriveApp.createFile(attachmentBlob)
           parentFolder.addFile(file); 
           root.removeFile(file); 
        }
        // Let's change the format and insert a "Hello world" message
        // ----START----
        var spreadSheetResponse = convertExceltoGoogleSpreadsheet(parentFolder);
        var spreadSheetId = spreadSheetResponse.getId()
        var sheet = SpreadsheetApp.openById(spreadSheetId).getSheets()[0];
        sheet.getRange(1, 1).setValue("Hello world");
        // ----END----
...

通知

在我的代码中,我将 .xlsx 文件留在了云端硬盘中,如果您愿意,可以在将其转换为原生 Google 电子表格格式后将其删除

文档

这是我曾经帮助你的:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2022-01-19
    • 2014-05-13
    相关资源
    最近更新 更多