CSV imports to different sheets based on number of columns

54 views Asked by At

I am trying to import 3 different .CSV files into an automated "Import CSV Sheet" using Google Apps Script. I am trying to modify the "append sheet" to append to a specific sheet within the spreadsheet based on the number of columns in the .CSV file.

I have tried using If/Else state but it seems to be ignored due to the fact that it is a Try/Catch statement (to which I am fairly unfamiliar with). Any suggestions on how to modify the try statement so that it will look at the number of columns, then append the correct sheet. Currently the function breaks at the first "if" statement even if the csv file has the correct number of columns.

function processCsv_(objSpreadSheet, csvFile) {

    try {
        // Gets the first sheet of the destination spreadsheet.
        let sheetVisits = objSpreadSheet.getSheets()[0];
        let sheetPay = objSpreadSheet.getSheets()[1];
        let sheetInv = objSpreadSheet.getSheets()[2];
  
        // Parses CSV file into data array.
        let data = Utilities.parseCsv(csvFile.getBlob().getDataAsString());

        // Omits header row if application variable CSV_HEADER_EXIST is set to 'true'.
        if (CSV_HEADER_EXIST) {
            data.splice(0, 1);
        }

        // Gets the row and column coordinates for next available range in the spreadsheet. 
        let startRowV = sheetVisits.getLastRow() + 1;
        let startRowP = sheetPay.getLastRow() + 1;
        let startRowI = sheetInv.getLastRow() + 1;
        let startCol = 1;

        // Determines the incoming data size.
        let numRows = data.length;
        let numColumns = data[0].length;

        // Appends data into the sheet.
        if (numColumns == 23) {
            sheetVisits.getRange(startRowV, startCol, numRows, numColumns).setValues(data);
            return true; // Success.
        } else if (numColumns == 11) {
            sheetPay.getRange(startRowP, startCol, numRows, numColumns).setValues(data);
            return true; // Success.
        } else if (numColumns == 9) {
            sheetInv.getRange(startRowI, startCol, numRows, numColumns).setValues(data);
            return true; // Success.
        }
    } catch {
        return false; // Failure. Checks for CSV data file error.
    }
}
0

There are 0 answers