Reputation: 1
I have written a function to import the content of a ".CSV" file into Google Sheet, and it does work fine 90% of the time. Here is the code I am using:
function listCsvFiles() {
var files = DriveApp.getFilesByType(MimeType.CSV);
var fileList = [];
while(files.hasNext()){
var file = files.next();
var fName = file.getName();
fileList.push(" \\n" + fName);
}
return fileList;
}
function importFromCSV() {
var fileName = Browser.inputBox("Enter the name of the data file in your Google Drive,\\n"
+"for example:\\n"
+ listCsvFiles(), Browser.Buttons.OK_CANCEL);
var searchTerm = "title = '"+fileName+"'";
// searching for the file
var files = DriveApp.searchFiles(searchTerm);
var csvFile = "";
// Looping through the results
while (files.hasNext()) {
var file = files.next();
// assuming the first is the one we want
if (file.getName() == fileName) {
// get file as a string
csvFile = file.getBlob().getDataAsString();
break;
}
}
// parseCsv returns a [][] array writable to a sheet
var csvData = Utilities.parseCsv(csvFile);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// dropping the data to a sheet
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
However, after multiple successful executions, randomly will throw the following error: "TypeError: Cannot read property 'length' of undefined"
I can't explain to myself why it works OK most of the time, but then throws an error. Please bear in mind the above code is bonded to a spreadsheet. Closing the spreadsheet and then opening it again is the remedy for now, but trying to figure out why it happens in the first place. Any suggestions are welcome and please do not judge me too hard as I am a beginner.
Upvotes: 0
Views: 159
Reputation: 85
I would try to catch the error like:
if(csvData != null){
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}else{
Logger.log(csvData);
}
After the error occurs, you can check the log and check the file that was causing the problem.
For me it looks like you trying to use a csvFile which was not found a or something else is going wrong in this line: csvFile = file.getBlob().getDataAsString();
Upvotes: 1