Duplicate Rows in Google Spreadsheet based on Value

こ雲淡風輕ζ 提交于 2019-11-30 16:14:34

问题


I'm trying to programatically duplicate rows in a Google spreadsheet. I would like the number of times the row is duplicated to be based on one of the values in the row itself.

For example, lets say I have a table like this:

You can see that there are numbers in column C. The value in column C is the number of times I would like to duplicate the row. This is what the desired result would look like:

Technically, if the value in column C was 3, we would be duplicating the row two times.

Any ideas on how to script a Google spreadsheet to do this would be great!

Thanks!


回答1:


This is fairly simple and you should have tried it yourself. I'm sure that when you'll read the code below you'll say "Oh, of course, I could have done it easily"... right ?

function autoDup() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var newData = [];
  for(var n in data){
    newData.push(data[n]);
    if(!Number(data[n][2])){continue};// if column 3 is not a number then do nothing
    for(var c=1 ; c < Number(data[n][2]) ; c++){ // start from 1 instead of 0 because we have already 1 copy
      newData.push(data[n]);//store values
    }
  }
  sheet.getRange(1,1,newData.length,newData[0].length).setValues(newData);// write new data to sheet, overwriting old data
}



回答2:


Assuming your input is on inSheet, on a different sheet you can place the following formula =transpose(split(arrayformula(textjoin(",",false,iferror(rept(inSheet!A1:A&",",inSheet!$C1:$C)))),",")) and drag it right twice and you're done. This could be bulletproofed to handle empty cells or ones with commas or repeat values of 0, but for nice data like above, it works as is.



来源:https://stackoverflow.com/questions/25396824/duplicate-rows-in-google-spreadsheet-based-on-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!