Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split multiline text to rows using app script?

I use a 3rd APP with spreadsheet as database. Each time the app executed, it will return data as multiline text shown below:
| Code | Name | Date | Task | Unit | progress |
| ——– | ——– | ——– | ——– | ——– | ——– |
|code1
code2
code3|user1
user2
user3|date1
date2
date3|task1
task2
task3|unit1
unit2
unit3|done
ongoing
need revision|
(PS: I saw my first column was mess after I post it, so I give this image of the data returned from the app, just in case the table not load properly)
multiline text table

I need to split the multiline data in to rows using app script, so it should look like this,

Code Name Date Task Unit progress
code1 user1 date1 task1 unit1 done
code2 user2 date2 task2 unit2 ongoing
code3 user3 date3 task3 unit3 need revision

I know simple script like how to split text to columns using delimiter, for example like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function myFunction() {
  
  var ss= SpreadsheetApp.getActiveSpreadsheet();
  var sh= ss.getSheetByName('Sheet1');
  var lr= sh.getLastRow();
  var range1= sh.getRange('A2:A' + lr);
  range1.splitTextToColumns('\n');

}

But it’s just split the the text to columns, not to the row below, and obviously it won’t not work for the array of data. How can I split multiline text to rows using app script?

Thank you in advance.

>Solution :

In your situation, how about the following sample script?

Sample script:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName('Sheet1');

  // --- I modified the below script.
  var values = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
  var newValues = values.flatMap(r => {
    var temp = r.map(c => c.split("\n").map(d => d.trim()));
    var maxLen = Math.max(...temp.map(e => e.length));
    temp = temp.map(e => e.length < maxLen ? [...e, Array(maxLen - e.length).fill(null)] : e);
    return temp[0].map((_, col) => temp.map((row) => row[col] || null));
  });
  sh.getRange(2, 1, newValues.length, newValues[0].length).clearContent().setValues(newValues);
}

Testing:

When this script is run with your provided sample table, the following result is obtained.

enter image description here

References:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading