Library or standard function for parsing a sheet data into CSV Format

16 views
Skip to first unread message

Matt McDonald

unread,
Jun 4, 2020, 5:41:25 PM6/4/20
to Google Apps Script Community
I am trying to pull data from a sheet and parse it into CSV format and update a CSV file in Google Drive. This is all working with the below function. But the issue I am having is that within some of the cells, I have line breaks. It's like a Notes column, so most of the cells have full paragraphs. Would anyone be able to help me figure out how to maintain these cells as a singular value within the CSV?

Or is there a GAS library out there that could do the hard work for me? If I download the sheet manually from the menu as a csv, its parsed perfectly, so I'm assuming there is logic somewhere that makes this work!

function convertRangeToCsvFile(sheet) {
  var activeRange=sheet.getDataRange();
  var data=activeRange.getValues();
  
  if (data.length>1) {
    var csv="";
    for(var row=0;row<data.length;row++) {
      for (var col=0;col<data[row].length; col++) {
        if (data[row][col].toString().indexOf(",") != -1) {
          data[row][col]="\"" + data[row][col] + "\"";
        }
      }
      if (row<data.length-1){csv += data[row].join(",") + "\r\n";
                            }else {csv += data[row];}
    }
    var testfiles = DriveApp.getFilesByName('testfile.csv');
    while (testfiles.hasNext()) {
      var testfile = testfiles.next();
    }

    testfile.setContent(csv);
  }
  return testfile.getId();
}

Reply all
Reply to author
Forward
0 new messages