How to add data to a specific row in Google Sheets using Google Script

老子叫甜甜 提交于 2019-12-24 09:13:14

问题


In my Google Sheet, I have the index in a variable called colorRow. And i'm just trying to add some data to that row in the sheet but the data keeps going to some other row down the page. What am I doing wrong?

var data = [];
// Some more fields in data array
data.push("Final Submission Date: " + new Date());
// target_sheet.insertRowAfter(colorRow); // Tried this didn't work
target_sheet.appendRow(data);

I need to figure out some way to either reset the append counter so that I can set it to row {colorRow} or if there is a way I can add to a specific row, maybe something like

target_sheet.addAt(7, data)

Something like this would be ideal.


回答1:


You can not use appendRow to do what you want. You are using:

target_sheet.appendRow(data);

You need to use setValues()

target_sheet(start row, start column, number of rows, number of columns).setValues(data);

In your case, if you want to overwrite (edit) an existing row, then you will need to find the row with the index in it, and use that number for the start row parameter.

var data, dataAs1D,dataFromCol1,ouss, target_sheet, lastRow,rowToEdit;

ss = SpreadsheetApp.getActiveSpreadsheet();
target_sheet = ss.getSheetByName('name');

lastRow = target_sheet.getLastRow();

dataFromCol1 = target_sheet.getRange(1,1,lastRow,1).getValues();//Get all col A values
dataAs1D = dataFromCol1.toString().split(",");//Convert 2D array to 1D

rowToEdit = colorRow;//

data = ['one','two','three'];
outerArray = [];//Assign empty array to variable name
outerArray.push(data);
target_sheet.getRange(rowToEdit,1,data[0].length,data.length).setValues(data);

This example assumes that your index numbers are in column one.



来源:https://stackoverflow.com/questions/42912227/how-to-add-data-to-a-specific-row-in-google-sheets-using-google-script

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