I need to open excel files in given google drive folder and read its data. For that, I used the following code.
var folders = DriveApp.getFoldersByName("Test Folder");
var foldersnext = folders.next();
var files = foldersnext.getFiles(); // get all files from folder
while(files.hasNext()) {
var sheets = SpreadsheetApp.openByUrl(files.next().getUrl()); // Line A
}
But it gives an error in "Line A" like this;
Document 1LDVkBTnkcY32ni9WoGDn6xHonPOX87ZV is missing (perhaps it was deleted, or you don't have read access?)
But when Log the IDs of the files using,
var selectedFile = files.next();
Logger.log(selectedFile.getId());
It gives me the expecting result. So, I think the error is in converting the file to excel file. Please give me a solution to open multiple excel files in a given folder and read its data...
This project has the following scopes
If my understanding is correct, how about this modification?
Drive.Files.copy()
for converting from Excel file to Google Spreadsheet.When you run the script, please enable Drive API at Advanced Google Services as follows. This modified script used Drive API of Advanced Google Services.
Please modify your script as follows.
From:while(files.hasNext()) {
var sheets = SpreadsheetApp.openByUrl(files.next().getUrl()); // Line A
}
To:
while(files.hasNext()) {
var file = files.next();
if (file.getMimeType() == MimeType.MICROSOFT_EXCEL || file.getMimeType() == MimeType.MICROSOFT_EXCEL_LEGACY) {
var resource = {
title: file.getName(),
parents: [{id: foldersnext.getId()}],
mimeType: MimeType.GOOGLE_SHEETS
};
var spreadsheet = Drive.Files.copy(resource, file.getId());
var sheets = SpreadsheetApp.openById(spreadsheet.id);
}
}
Drive.Files.remove(fileId)
.If I misunderstood your question and this was not the result you want, I apologize.
From your comment, it was found that my understanding was correct. So as a test case, can you test the following flow?
Run the following sample script. Before run it, please set the folder ID.
function sample() {
var folderId = "###"; // Please set the folder ID.
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
while(files.hasNext()) {
var file = files.next();
if (file.getMimeType() == MimeType.MICROSOFT_EXCEL || file.getMimeType() == MimeType.MICROSOFT_EXCEL_LEGACY) {
var resource = {
title: file.getName(),
parents: [{id: folderId}],
mimeType: MimeType.GOOGLE_SHEETS
};
var spreadsheet = Drive.Files.copy(resource, file.getId());
var sheet = SpreadsheetApp.openById(spreadsheet.id).getSheets()[0];
var value = sheet.getDataRange().getValues();
Logger.log(value)
}
}
}
sample()
at the script editor.