Search code examples
javascriptarraysgoogle-apps-scriptgoogle-drive-apigoogle-apps-script-editor

App Script debug success but execution failed.Why?


I need to import csv files into specified google sheets from App scripts. I developed a code which works perfectly, but it does not show any output. What I did was I created an array to insert a list of csv files and another array to insert the sheet names in the active spreadsheet. then I created an if loop where the csv file containing array will push data if the index of that array equals to the index of array containing the sheets. I put this in an overall for loop to iterate. Below is my code.

function importCSVFromGoogleDrive() {

 var ss = SpreadsheetApp.getActiveSpreadsheet();// get the active spreadsheet


["Sheet1", "Sheet2", "Sheet3"].forEach(function (s) {
 var sheetArray = ss.getSheetByName(s);                   // getSheetByName


var numSheets = sheetArray.length; // save sheets in Array 


for (j = 0; j < numSheets; j++) { //loop to iterate

 var fileArray = DriveApp.getFilesByName["Acsv","Bcsv"]; //get csv files as a list 

 var file = fileArray.length; // add the list into an array

 var csvData = Utilities.parseCsv(file.getBlob().getDataAsString()); // parse csv data


 if(numSheets==csvData){  // if array Index No of numSheets equals to index of file array

    numSheets.push(csvData);// push csv data into the sheet


    numSheets.clearContents(); //clear current contents in the sheet
    numSheets.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData); // set values to the sheet
      }

   }

 })
}

The code does not show any errors but neither any data input to sheet from csv file. Can anyone explain why this happens like this please?


Solution

  • This line is using the wrong syntax of getFilesByName:

    var fileArray = DriveApp.getFilesByName["Acsv","Bcsv"]; //get csv files as a list 
    

    The correct syntax is:

    DriveApp.getFilesByName(name);
    

    Where name is a string. You should change your code accordingly.

    On the other hand

    var numSheets = sheetArray.length; // save sheets in Array 
    

    and

    var file = fileArray.length; // add the list into an array
    

    Assigns an integer to numSheets and file respectively, so the next code lines don't do what you expect, like

    numSheets.push(csvData);// push csv data into the sheet
    

    and

    var csvData = Utilities.parseCsv(file.getBlob().getDataAsString()); // parse csv data
    

    Consider to spare some time to learn how the Google Apps Script debugger works so you can use it to efficiently debug your code.

    Reference