Home > Enterprise >  Google Script to copy all csv files in a GDrive Folder as new sheets in existing 'master'
Google Script to copy all csv files in a GDrive Folder as new sheets in existing 'master'

Time:04-09

In my google drive I have a 'master' google worksheet and a sub-folder that gets anywhere from 1 to 20 .csv files added to it. I'm trying to write my google app script to take each of the .csv files in the folder and add them as individual sheets in the 'master' worksheet, with the tabs for each sheet being named the same as the name of the .csv file.

Example scenario: after 3 .csv files are added to the sub-folder (alpha.csv, bravo.csv, charlie.csv), we run the script from 'master' google sheet, which adds 3 tabs (named: alpha, charlie, bravo) with all of the corresponding data on the respective sheets.

What I have for code so far will get the file names and create sheets for each file with the correct name. I've tried researching here and am struggling to solve the data import part.

This is what I have to get the new tabs and names to match

// works to make a new sheet that is named to match the sheets inside of the folder
function runScript()  {
  var folder = DriveApp.getFolderById("googlefolderIDhere");
  var fileIterator = folder.getFiles();
  var file;
  var fn;
  var fileType;
  var fileID;
  var listSS = SpreadsheetApp.getActiveSpreadsheet();
    while(fileIterator.hasNext()){
      file = fileIterator.next();
      fn = file.getName();
      fileID = file.getId();
      fileType = file.getMimeType();
      if(fileType === "text/csv"){
        listSS.insertSheet(fn);   
      }
    }   
}

I found this code for getting the data but can't figure out how to use it with the above code

   var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
   sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);

CodePudding user response:

Loading a sheet with a 2D array obtained from parseCsv

function runScript() {
  const ss = SpreadsheetApp.getActive()
  const folder = DriveApp.getFolderById("googlefolderIDhere");
  const files = folder.getFiles();
  while (files.hasNext()) {
    let file = files.next();
    let fn = file.getName();
    let fileID = file.getId();
    let fileType = file.getMimeType();
    if (fileType === "text/csv") {
      let vs = Utilitiesl.parseCsv(file.getBlob().getDataAsString());
      let sh = ss.insertSheet(fn);
      if(sh) {
        sh.getRange(1, 1, vs.length, vs[0].length).setValues(vs);
      }
    }
  }
}
  • Related