我正在尝试将3个SpreadSheets保存为一个。为此,我必须检查3个文件是否存在。但我的代码不起作用:
function mergeSheets() {
var myFolder = DriveApp.getFoldersByName('myFolder').next();
var spreadSheets = myFolder.getFiles();
var file1 = "myfile1.xlsx";
var file2 = "myfile2.xlsx";
var file3 = "myfile3.xlsx";
while(spreadSheets.hasNext()) {
var sheet = spreadSheets.next();
if ( (sheet.getName()==file1) && (sheet.getName()==file2) &&
(sheet.getName()==file3)) {
var newSpreadSheet = SpreadsheetApp.create("myList");
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
for(var y in spreadSheet.getSheets()) {
spreadSheet.getSheets()[y].copyTo(newSpreadSheet);
}
// Rename sheets with string "Copy of fileX" to "fileX"
if (newSpreadSheet.getSheetByName('Kopie von file1') == true){
newSpreadSheet.getSheetByName('Kopie von file1').setName('file1')
}
if (newSpreadSheet.getSheetByName('Kopie von file2') == true){
newSpreadSheet.getSheetByName('Kopie von file2').setName('file2')
}
if (newSpreadSheet.getSheetByName('Kopie file3') == true){
newSpreadSheet.getSheetByName('Kopie von file3').setName('file3')
}
// Delete standard sheet if create a new spreadsheet
newSpreadSheet
.deleteSheet(newSpreadSheet.getSheetByName('Tabellenblatt1'))
var file = DriveApp.getFileById(newSpreadSheet.getId())
var folder = DriveApp.getFoldersByName('myFolder').next();
var newFile = folder.addFile(file);
DriveApp.getRootFolder().removeFile(file);
}
}
}
我不知道为什么这不起作用。如果我在没有AND-operator的if语句中使用在线的一个文件,它可以工作,但我认为这不是问题。
答案 0 :(得分:1)
您可以明确获取所有三个文件,排除所有其他文件。使用search()
方法:
function mergeSheets() {
var myFolder = DriveApp.getFoldersByName('myFolder').next();
var spreadSheets,thisFile;
var file1 = "myfile1.xlsx";
var file2 = "myfile2.xlsx";
var file3 = "myfile3.xlsx";
spreadSheets = myFolder.searchFiles('title contains "' + file1 +
'" or title contains "' + file2 +
'" or title contains "' + file3 + '"');
while(spreadSheets.hasNext()) {
thisFile = spreadSheets.next();
Logger.log('name: ' + thisFile.getName())
}
}
但我不认为获取一系列文件并循环遍历它们是最好的策略。如果文件数始终为3,并且您知道确切的文件名,那么您可能希望单独获取每个文件。
var myFolder = DriveApp.getFoldersByName('myFolder').next();
var file1 = myFolder.getFilesByName("myfile1.xlsx").next();
var file2 = myFolder.getFilesByName("myfile2.xlsx").next();
var file3 = myFolder.getFilesByName("myfile3.xlsx").next();