Moving rows from spreadsheets to new documents based on owner name with filling information in document

80 Views Asked by At

I have a spreadsheet named Project log where I have 6 columns,

Timestamp   Task    Owner   Date    Keywords    Email

Here we have different owners. I need to create a document with the owner name and move particular owner row to that owner document.

I am able to do this by looping but I had a issue when I get duplicate names it is creating another document and sending data but as per my requirement I need to have only one document on that particular owner and move duplicate owner name to owner itself.

Example of owner column.

  joe
  john
  john

Here I need to create a document with "joe" name and append body with that whole row but I have two "john"s I need to create only one document i.e., "john" and move two rows to single document if I find more on his name I should be able to send that row to that particular owner document.

And my looping code is:

function createDocFromSheet() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet =  ss.setActiveSheet(ss.getSheets()[2]);
    var numRows=ss.getLastRow();
    var values = ss.getDataRange().getValues()

    for(n=2;n<=values.length;++n) {
        var cell = sheet.getRange(n,3).getValue();
        var row = sheet.getRange(n,2,1,5).getValues();
        var newDoc = DocumentApp.create("Task Report - "+cell);
        var body = newDoc.getBody();
        body.insertParagraph(0,row);

        newDoc.saveAndClose(); 
    }
}
1

There are 1 best solutions below

2
On

If the name is repeating in the column for just once, you can get the firstIndex and lastIndex of the range array and check if those two positions matches or not.

Giving an algorithmic code below:

var array1 = sheet.getRange(1,3,sheets.getLastRow()).getValues();
(Example values might be like array1 = [a,b,c,a,c,d])
var var1 =  sheet.getRange(n,3).getValue();
var var2 = array1.indexOf(var1);
var var3 = array1.lastIndexOf(var1);


if(var2 == var3) {
// this means there is no repetition of the name.
}
else{
//get the values for both rows and create a document.
// Make a flag variable array to note that a doc is created with this name.
}

Hope that helps!