I try to split data in google sheet by row and create new sheet and transfer the data to new sheet. Here is my script sample:
var ss= getspreadsheetId();
var sheet = ss.getActiveSheet();
var data = sheet.getDataRange().getValues();
var lastRow = sheet.getLastRow();
var ui_user = SpreadsheetApp.getUi();
var result = ui_user.prompt("Enter split Number?");
var split_number=result.getResponseText();
var sheetName = ui_user.prompt("Enter Sheet name *Separate by space");
var sheetName_user =sheetName.getResponseText();
var sheetNamet_user_split=sheetName_user.split(" ");
data = sheet.getDataRange().getValues();
result = [];
//calculation to get row data split
split_value=Math.floor(lastRow/split_number);
//Logger.log(split_value);
for(i=0;i<split_number;i ){
for(j=0;j<split_value;j ){
result.push(data[j]);
}
ss.insertSheet(sheetNamet_user_split[i]);
var sheetAdd = ss.getSheetByName(sheetNamet_user_split[i]);
sheetAdd.getRange(1,1,result.length,result[0].length).setValues(result);
result=[]
}
The problem in this script is i only able to display same data for every sheet that created. is there any way i can increment the iteration so it can iterate new data?
CodePudding user response:
Modification points:
- In your script, the same values are used by
for (j = 0; j < split_value; j ) { result.push(data[j]); }
. I think that this is the reason for your issue ofThe problem in this script is i only able to display same data for every sheet that created.
. insertSheet
method returns the inserted Sheet object.- When the number of inputted sheet names is more than the split values, the empty sheets are inserted.
When these points are reflected in your script, how about the following modification?
From:
data = sheet.getDataRange().getValues();
result = [];
//calculation to get row data split
split_value=Math.floor(lastRow/split_number);
//Logger.log(split_value);
for(i=0;i<split_number;i ){
for(j=0;j<split_value;j ){
result.push(data[j]);
}
ss.insertSheet(sheetNamet_user_split[i]);
var sheetAdd = ss.getSheetByName(sheetNamet_user_split[i]);
sheetAdd.getRange(1,1,result.length,result[0].length).setValues(result);
result=[]
}
To:
var data = sheet.getDataRange().getValues();
var split_value = Math.floor(lastRow / split_number);
sheetNamet_user_split.forEach(e => {
var values = data.splice(0, split_number);
if (values.length > 0) {
var sheetAdd = ss.insertSheet(e.trim());
sheetAdd.getRange(1, 1, values.length, values[0].length).setValues(values);
}
});
- In this modification, in order to use each split value, I used
splice()
.