【发布时间】:2021-11-12 03:32:00
【问题描述】:
我正在从共享驱动器访问文件夹列表。
在这里,我将一些 excel 文件转换为电子表格。我的问题是用新文件替换旧的转换文件。这是因为每次我运行脚本时,新转换的文件(具有相同名称)都会在同一个文件夹中与旧文件一起不断增加。
代码如下:
function ConvertFiles() {
var sheet =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var r= 2;
for(r= 2;r < sheet.getLastRow(); r++){
// Use getValue instead of getValues
var fileId = sheet.getRange(r,1).getValue();
var folderID = sheet.getRange(r,8).getValue();
var files = DriveApp.getFileById(fileId);
var name = files.getName().split('.')[0];
var blob = files.getBlob();
var newFile = {
// Remove '_converted' from name if existing to avoid duplication of the string before adding '_converted'
// This will allow to have newly converted file "replace" the old converted file properly
title: name.replace('_converted','') + '_converted',
parents: [{
id: folderID
}]
};
var destinationFolderId = DriveApp.getFolderById(folderID);
var existingFiles = destinationFolderId.getFilesByName(newFile.title);
// GOAL #1: To replace/update the old converted file into the latest one everytime the script runs (if it has the same filename)
// Find the file with same name of the file to be converted
while(existingFiles.hasNext()) {
// ID of the file with same converted name
var oldConvertedFileWithSameNameID = existingFiles.next().getId();
// Delete before writing
Drive.Files.remove(oldConvertedFileWithSameNameID);
//DriveApp.getFileById(oldConvertedFileWithSameNameID.getId()).setTrashed(true);
}
// Create new converted file then get ID
var newFileID = Drive.Files.insert(newFile, blob, { convert: true,supportsAllDrives: true }).id;
Logger.log(newFileID);
//var sheetFileID = newFileID.getId();
//var Url = "https://drive.google.com/open?id=" + sheetFileID;
var Url = "https://drive.google.com/open?id=" + newFileID;
// Add the ID of the converted file
sheet.getRange(r,9).setValue(newFileID);
sheet.getRange(r,10).setValue(Url);
}
}
我的目标是
- 将旧转换文件替换为新文件(如果它们具有相同名称)到共享驱动器文件夹中
- 要了解如何在上述代码中实现 setTrashed()
我尝试使用Drive.Files.remove(oldConvertedFileWithSameNameID);,但收到错误消息GoogleJsonResponseException: API call to drive.files.delete failed with error: File not found:("fileid")。然后我看到一个关于这个[https://stackoverflow.com/questions/55150681/delete-files-via-drive-api-failed-with-error-insufficient-permissions-for-this]的问题......所以我猜该方法不适合在共享文件夹中实现。
那么我如何在上述代码中使用setTrashed() 方法?
【问题讨论】:
-
如果我们从“我的驱动器”文件夹中检索我们的文件,上面的代码运行良好.....但是如果我们使用“与我共享”部分中的文件夹,这意味着作为共享文件夹我如上所述,出现错误。
标签: google-apps-script google-sheets google-drive-shared-drive