Google电子表格中基于值的重复行 [英] Duplicate Rows in Google Spreadsheet based on Value
问题描述
我正在尝试以编程方式复制Google电子表格中的行.我希望重复行的次数基于行本身中的值之一.
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:
您可以看到C列中有数字.C列中的值是我想要重复该行的次数.这就是预期的结果:
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:
从技术上讲,如果C列中的值为3,我们将把该行复制两次.
Technically, if the value in column C was 3, we would be duplicating the row two times.
任何有关如何编写Google电子表格脚本以实现此目的的想法都很棒!
Any ideas on how to script a Google spreadsheet to do this would be great!
谢谢!
推荐答案
这很简单,您应该自己尝试一下.我确定当您阅读下面的代码时,您会说:哦,当然,我可以很轻松地做到这一点"……对吗?
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
}
这篇关于Google电子表格中基于值的重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!