Google Script: Creating Bulk folders from Spreadsheet

186 Views Asked by At

Need Help, I am looking to create bulk folders in my google drive from the information mentioned in the spreadsheet. The spreadsheet has header of Column "A" as Name, Column "B" as Description, Column "C" as Parent folder Name, and Column "D" as to whether its Root or No.

After running the script it does two things. 1: Gives error of "Exception: Argument cannot be null: description" 2: It creates only one folder and with name as the first letter only. e.g Row 2 in Column "A" has name 'abcd' and Row 3 in Column "A" has the name 'XYZ'. The scripts only create a folder from Row 2 with the name 'A' not abcd.

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('GDrive')
  .addItem('Create new Folders', 'crtGdriveFolder')
  .addToUi();
}

function crtGdriveFolder() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;
  var numRows = sheet.getLastRow();
  var maxRows = Math.min(numRows,20);
  var folderid = sheet.getRange("C2").getValue();
  var root = sheet.getRange("D2").getValue();
  var dataRange = sheet.getRange(startRow, 1, maxRows, 2);
  var data = dataRange.getValue();
  var folderIterator = DriveApp.getFoldersByName(folderid);

  if(!folderIterator.hasNext()) {
    SpreadsheetApp.getActiveSpreadsheet().toast('Folder not Found!');
    return;
  }

  var parentFolder = folderIterator.next();

  if(folderIterator.hasNext()) {
    SpreadsheetApp.getActiveSpreadsheet().toast('Folder has a non-unique name!');
    return;
  }

  for (i in data) {
    var row = data[i];
    var name = row[0];
    var desc = row[1];



  if(root == "N" && name != "") {
      var idNewFolder = parentFolder.createFolder(name).setDescription(desc).getId();
      ////Utilities.sleep(100);
      var newFolder = DriveApp.getFolderById(idNewFolder);

      } if(root == "Y" && name != "") {
        var idNewFolder = DriveApp.createFolder(name).setDescription(desc).getId();
        Utilities.sleep(100);
        var newFolder = DriveApp.getFolderById(idNewFolder);
      }
  }
}
2

There are 2 best solutions below

1
On

As Micheil has mentioned in the comment, just change var data = dataRange.getValue(); to var data = dataRange.getValues(); and it should work. Currently it is only getting value of a single cell rather than the range. That's why when you try to get name using var name = row[0]; it only returns a single char of that cell value. And no, var maxRows = Math.min(numRows,20); will not cause an issue even if there are less than 20 rows.

0
On

Try var data = dataRange.getValues(); (getValueS, plural so with a S at the end) instead of getValue (single)

And you use var maxRows = Math.min(numRows,20);. Is it possible that at times you have less than 20 rows of data in your range? If so, it will find blank rows.