0

I created a script based off this one which takes a CSV attachment from Gmail and then pastes it into a Google Sheet, and when I try use the script again on a new sheet it gives me an error:

Exception: Cannot convert ',' to char. (line 22, file "Code")

Line of code:

  var csvData = Utilities.parseCsv(attachment.getDataAsString(), ',');

The thing I find really weird I have the exact same line of code in other scripts and they work without issue. I've even tried copy/pasting the line of code from the working scripts.

function importCSVFromGmail() {
  var threads = GmailApp.search("redacted");
  var message = threads[0].getMessages().pop();

  var attachment = message.getAttachments()[0];

  if (attachment != null) {
    var attachName = attachment.getName();

    // Is the attachment a CSV file
    if (attachName.substring(attachName.length-4) === ".csv") {
      var id = "redacted";
      var name = "Data Sheet";
      var sheet = SpreadsheetApp.openById(id);
      var tab = sheet.getSheetByName(name);
      

      // Clear the content of the sheet
      var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
      tab.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
  } 
}

Any help would be appreciated, I can't figure out why I'm getting the error only in new scripts.

Cooper
  • 59,616
  • 6
  • 23
  • 54
Mo4735
  • 73
  • 4

2 Answers2

1

Just as @TheMaster suggested, you should change your line of code from this

var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");

to this

var csvData = Utilities.parseCsv(attachment.getDataAsString());

You can also read more about the .parseCsv() function here.

ale13
  • 5,679
  • 3
  • 10
  • 25
0

I don't think removing the parameter is the best solution.

Here is the definition from Google: parseCsv(csv, delimiter)

Here is my solution:

var csvData = Utilities.parseCsv(attachment.getDataAsString(), ','.charCodeAt(0));

Note: Removing the parameter in your example may have no difference as ',' is the default delimiter in this function. It may make a lot more sense on a situation that you need another delimiter like ';'