Search code examples
csvgoogle-apps-scriptimportgoogle-sheets-apistring-comparison

How can I import multiple CSVs to preset sheets?


I have some CSV files on my G-drive that I want to import to preset sheets, based on file names. For example,

  1. I have CSV files named: "REP1-abc", "REP2-bcd", "REP3-cde",...
  2. I have spreadsheet with sheets named: "REP1", "REP2", "REP3",...

Target is to take first four letters of file name to match correct sheet name and import it to that sheet. Im new in this so i will appreciate any tips on how to compare those two names.


Solution

  • Loading CSVs

    function loadcsvs() {
      const fldr = DriveApp.getFolderById("Folder id");
      const files = fldr.getFileByType(MimeType.CSV);
      const ss = SpreadsheetApp.getActive();
      const shts = ss.getSheets().map(sh => sh.getName());
      while(files.hasNext()) {
        let file = files.next();
        let sname = file.getName().slice(0,4);
        let idx = shts.indexOf(sname);
        if(~idx) {
          let sht = ss.getSheetByName(shts[idx]);
          let vs = Utilities.parseCsv(file.getBlob().getDataAsString())
          sht.getRange(1,1,vs.length,vs[0].length).setValues(vs);
        }
      }
    }