我正在訪問共享驅動器中的檔案夾串列。
在這里,我將一些 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()
I have tried using the Drive.Files.remove(oldConvertedFileWithSameNameID); but I am getting an error message GoogleJsonResponseException: API call to drive.files.delete failed with error: File not found:("fileid"). Then i saw an question on this [https://stackoverflow.com/questions/55150681/delete-files-via-drive-api-failed-with-error-insufficient-permissions-for-this]...so i guess that method is not suitable to implemented in shared folder.
So i how can i use setTrashed() method inside the above code?
uj5u.com熱心網友回復:
我認為您需要設定supportsAllDrives引數:
Drive.Files.remove(oldConvertedFileWithSameNameID, {supportsAllDrives: true});
參考:
- 檔案:洗掉 | Google 云端硬碟 API | Google Developers - 引數
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/358826.html
標籤:google-apps-script google-sheets google-drive-shared-drive
