Apps Script Utilities.parseCsv assumes new row on line breaks within double quotes

前端 未结 5 828
渐次进展
渐次进展 2020-12-18 08:39

When using Utilities.parseCsv() linebreaks encased inside double quotes are assumed to be new rows entirely. The output array from this function will have sever

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 09:44

    To avoid trying to understand regular expressions, I found a workaround below, not using Utilities.parseCsv(). I'm copying the data line by line.

    Here is how it goes:

    If you can find a way to add an extra column to the end of your CSV, that contains the exact same value all the time, then you can force a specific "line break separator" according to that value.

    Then, you copy the whole line into column A and use google app script' dedicated splitTextToColumns() method...

    In the example below, I'm getting the CSV from an HTML form. This works because I also have admin access to the database the user takes the CSV from, so I could force that last column on all CSV files...

    function updateSheet(form) {
      var fileData = form.myFile;
      // gets value from form
      blob = fileData.getBlob();
      var name = String(form.folderId);
      // gets value from form
    
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.setActiveSheet(ss.getSheetByName(name), true);
    
      sheet.clearContents().clearFormats();
    
      var values = [];
      // below, the "Dronix" value is the value that I could force at the end of each row
      var rows = blob.contents.split('"Dronix",\n');
    
      if (rows.length > 1) {
        for (var r = 2, max_r = rows.length; r < max_r; ++r) {
          sheet.getRange(r + 6, 1, 1, 1).setValue(String(rows[r]));
        }
      }
    
      var spreadsheet = SpreadsheetApp.getActive();
      spreadsheet.getRange("A:A").activate();
      spreadsheet.getRange("A:A").splitTextToColumns();
    }
    

提交回复
热议问题