javascript Google 应用程序脚本 AppendRow 到顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28295056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google apps script AppendRow to the top
提问by Dmitrij Holkin
As I know
我所知
appendRow(rowContents) add values to the bottom of the spreadsheet But how to add data from form in multiple rows in top of spreadsheet?
appendRow(rowContents) 将值添加到电子表格的底部但是如何从电子表格顶部的多行表单中添加数据?
So if in form i have rows
所以如果在表格中我有行
- first, surname, name
- second, surname, name
- third, surname, name
- 第一, 姓氏, 名字
- 二、姓、名
- 三、姓氏
in sheet it must be placed as, and each time to the top
在工作表中,它必须放置为,并且每次都放在顶部
so if another time in form will be
所以如果另一个时间形式将是
- fourth, surname, name
- fifth, surname, name
- six, surname, name
- 四、姓氏
- 五、姓氏
- 六、姓氏
data will be added like
数据将被添加,如
Now I using this code, but it append all data to the end and works only with one row, i think i must loop throught all rows in form but how to do that?
现在我使用此代码,但它将所有数据附加到最后并且仅适用于一行,我想我必须循环遍历表单中的所有行,但如何做到这一点?
function getValuesFromForm(form){
var firstName = form.firstName,
lastName = form.lastName,
order = form.order,
sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.appendRow([order,lastName,firstName]);
}
回答by Henrique G. Abreu
There's no single function to do this, but it's not that difficult write one. Here's an example:
没有单一的函数可以做到这一点,但编写一个函数并不难。下面是一个例子:
function prependRow(sheet, rowData) {
sheet.insertRowBefore(1).getRange(1, 1, 1, rowData.length).setValues([rowData]);
}
I would actually allow for an optional index, let's say we want to insert after the 2nd row, skipping the header.
我实际上会允许一个可选的索引,假设我们想在第二行之后插入,跳过标题。
function insertRow(sheet, rowData, optIndex) {
var index = optIndex || 1;
sheet.insertRowBefore(index).getRange(index, 1, 1, rowData.length).setValues([rowData]);
}
But appendRow
also has another interesting characteristic, it's concurrent-safe. Which means it can be triggered multiple times in parallel and won't mess up. To make our function concurrent safe you have to lock
it, like this:
但appendRow
还有另一个有趣的特性,它是并发安全的。这意味着它可以并行触发多次并且不会搞砸。为了使我们的函数并发安全,你必须这样lock
做,像这样:
function insertRow(sheet, rowData, optIndex) {
var lock = LockService.getScriptLock();
lock.waitLock(30000);
try {
var index = optIndex || 1;
sheet.insertRowBefore(index).getRange(index, 1, 1, rowData.length).setValues([rowData]);
SpreadsheetApp.flush();
} finally {
lock.releaseLock();
}
}
Then, to use it in your code just call..
然后,要在您的代码中使用它,只需调用..
function getValuesFromForm(form){
//...
insertRow(sheet, [order,lastName,firstName]); //could have passed an extra `2` parameter to skip a one line header
}