Google apps script 如果文件已存在于Google Drive中,则跳过处理.xls到Google Sheets脚本
我目前正在使用此代码自动将Google Drive中所有上载的.xls文件转换为Google工作表Google apps script 如果文件已存在于Google Drive中,则跳过处理.xls到Google Sheets脚本,google-apps-script,google-sheets,google-drive-api,Google Apps Script,Google Sheets,Google Drive Api,我目前正在使用此代码自动将Google Drive中所有上载的.xls文件转换为Google工作表 function importXLS(){ var files = DriveApp.searchFiles('title contains ".xls"'); while(files.hasNext()){ var xFile = files.next(); var name = xFile.getName(); if (name.indexOf('.xls')&
function importXLS(){
var files = DriveApp.searchFiles('title contains ".xls"');
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
if (name.indexOf('.xls')>-1){
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = { title : name,
key : ID,
'parents':[{"id":"12FcKokB-ppW7rSBtAIG96uoBOJtTlNDT"}]
}
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
}
}
}
它工作正常,但如果输出文件夹中已有同名文件,则会失败。尽管我从未在技术上看到下面这个错误,因为它是按计划运行的,并且没有像屏幕截图中那样手动触发,但如果文件已经存在,我宁愿跳过转换过程
如果可能的话,我也希望避免每次都覆盖它,因为我觉得那样会浪费处理时间。如果文件夹中已经存在文件名,我将如何编辑这段代码,以便完全跳过整个代码
谢谢 您可以尝试两件事: 获取目标文件夹中已存在的文件名,并在尝试复制之前检查该文件是否存在。 在try..catch语句中包装执行复制的代码部分。 这两种方法都应该独立工作,但使用try..catch语句将捕获所有错误,因此最好将它们结合起来。您可以在开发人员控制台中查看。执行此操作后,您将能够跳过与目标文件夹中已有文件同名的文件,并且可能出现的任何其他错误都不会终止脚本的完成
function importXLS(){
var files = DriveApp.searchFiles('title contains ".xls"');
var destinationFolderId = "12FcKokB-ppW7rSBtAIG96uoBOJtTlNDT";
var existingFileNames = getFilesInFolder(destinationFolderId);
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
try {
if (!existingFileNames[name] && (name.indexOf('.xls')>-1)) {
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = { title : name,
key : ID,
'parents':[{"id": destinationFolderId}]
}
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
}
} catch (error) {
console.error("Error with file " + name + ": " + error);
}
}
}
/**
* Get an object of all file names in the specified folder.
* @param {string} folderId
* @returns {Object} files - {filename: true}
*/
function getFilesInFolder(folderId) {
var folder = DriveApp.getFolderById(folderId);
var filesIterator = folder.getFiles();
var files = {};
while (filesIterator.hasNext()) {
var file = filesIterator.next();
files[file.getName()] = true;
}
return files;
}
您可以使用另一个if语句检查输出文件夹,比较当前文件名和文件夹中的现有文件。你可以试试这本书中的建议答案。这本书非常有效,谢谢。你是一个传奇人物,你有地方可以让我给你小费吗?哈哈,不用担心: