-1

Dear Stackoverflow community,

I am having troubles merging 2 separate scripts into a single one. Both are working fine if run individually, but not if both are present in a single file. The first script imports CSV into my spreadsheet to a temporary sheet called "Imported". The second script imports rows from "Imported" to the permanent sheet called "Main" and then deletes the temporary sheet.

I have tried to merge both scripts under the same function, but that only gives as an output "Imported" sheet without populating the main one. Same happens if I create a new function, which first calls function import CSV and then calls function import to Main.

For CSV import, I am using the following script, sourced from here:

function importCSV() {
var fSource = DriveApp.getFolderById('folder_id_removed'); 
// reports_folder_id = id of folder where csv reports are saved
var fi = fSource.getFilesByName('data.csv'); 
// latest report file
var ss = SpreadsheetApp.openById('spreadsheet_id_removed'); 
// data_sheet_id = id of spreadsheet that holds the data to be updated with new report data

if ( fi.hasNext() ) { // proceed if "report.csv" file exists in the reports folder
var file = fi.next();
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv); // see below for CSVToArray function
var newsheet = ss.insertSheet('Imported'); // create a 'NEWDATA' sheet to store imported data
// loop through csv data array and insert (append) as rows into 'NEWDATA' sheet
for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
  newsheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
  }

  }
};

function CSVToArray( strData, strDelimiter ) {
// Check to see if the delimiter is defined. If not,
// then default to COMMA.
strDelimiter = (strDelimiter || ";");

// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
  // Delimiters.
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

    // Standard fields.
    "([^\"\\" + strDelimiter + "\\r\\n]*))"
  ),
  "gi"
);

// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];

// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;

// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){

// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];

// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
  strMatchedDelimiter.length &&
  (strMatchedDelimiter != strDelimiter)
){

  // Since we have reached a new row of data,
  // add an empty row to our data array.
  arrData.push( [] );

}

// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){

  // We found a quoted value. When we capture
  // this value, unescape any double quotes.
  var strMatchedValue = arrMatches[ 2 ].replace(
    new RegExp( "\"\"", "g" ),
    "\""
  );

} else {

  // We found a non-quoted value.
  var strMatchedValue = arrMatches[ 3 ];

}

// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}

// Return the parsed data.
return( arrData );
};

To import rows from "Imported" to "Main", I have created this script:

function importRows() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Imported');
  var des=ss.getSheetByName('Main');
  var src=sh.getRange('A2:F500');
  var vA=src.getValues();
  for(var i=0;i<vA.length;i++) {
    if(vA[i].join("")) {
      des.appendRow(vA[i]);
    }
  }
  ss.deleteSheet(sh)
} 

I suspect that some minor change is required to CSV import script, but unfortunately, I am not experienced enough to find the answer myself.

Could anyone help me create a single script containing both of those functions? I will appreciate any help regarding this matter.

Egor P
  • 19
  • 7

2 Answers2

0

@Egor P - you can't exactly just combine the two scripts that way. If the two sheets are on the same spreadsheet you should be able to run the second function from a new project: File>New>Project.

You could set the second function as an onEdit(e) rather than importRows() This means as soon as your import from CSV has finished it should have already copied to the permanent sheet.

Hope this helps!

Gav
  • 328
  • 5
  • 17
0

Try this:

function importCSV() {
  var fSource=DriveApp.getFolderById('folder_id_removed'); 
  var fi=fSource.getFilesByName('data.csv'); 
  var ss=SpreadsheetApp.openById('spreadsheet_id_removed'); 
  if (fi.hasNext()) { 
    var file=fi.next();
    var csv=file.getBlob().getDataAsString();
    var csvData=CSVToArray(csv);
    var tsh=ss.getSheetByName('Main');
    for (var i=1;i<csvData.length;i++) {
      tsh.appendRow(csvData[i]);
    }
  }
}

Forget about Imported just put right into the Main.

Cooper
  • 59,616
  • 6
  • 23
  • 54