Reputation: 2019
I'm using below Nodejs code to insert some text to google spreadsheet, what I need to know is:
How can I make the code detect the first empty cell in specific column , for example first empty cell in column A, so I can start add my text to it, (or last cell which has value in column A, so I can start add my text after it)
Here you are existing code:
const mySpreadSheetId = 'mySheetId';
const range = 'Sheet2!A10';
return new Promise((resolve, reject) => {
sheets.spreadsheets.values.update({
auth: jwtClient,
spreadsheetId: mySpreadSheetId,
range: range,
valueInputOption: 'USER_ENTERED',
resource: {range: 'Sheet2!A10',
majorDimension: 'ROWS',
values: [["some Text"]]}
} ,(err, resp) => {
if (err) {
console.log('Data Error :', err);
reject(err);
}
resolve(resp);
});
});
Upvotes: 1
Views: 911
Reputation: 201748
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
In order to know the 1st empty row in the specific column, at first, the values are required to be retrieved. The flow of this modified script is as follows.
Please modify the script in new Promise((resolve, reject) => { ### })
as follows. Before you run the script, please set the variables of mySpreadSheetId
and sheetName
. In this modified script, the 1st empty cell of the column "A" is retrieved and the value of some Text
is put to the retrieved cell.
const mySpreadSheetId = 'mySheetId';
const sheetName = "Sheet2";
sheets.spreadsheets.values.get(
{
auth: jwtClient,
spreadsheetId: mySpreadSheetId,
range: `${sheetName}!A:A`
},
(err, res) => {
if (err) {
console.error(err);
return;
}
const data = res.data.values;
let i = 0;
for (i = 0; i < data.length; i++) {
if (!data[i][0]) break;
}
sheets.spreadsheets.values.update(
{
auth: jwtClient,
spreadsheetId: mySpreadSheetId,
range: `${sheetName}!A${i + 1}`,
valueInputOption: "USER_ENTERED",
resource: {
majorDimension: "ROWS",
values: [["some Text"]]
}
},
(err, resp) => {
if (err) {
console.log("Data Error :", err);
reject(err);
}
resolve(resp);
}
);
}
);
Above modified script retrieves the 1st empty cell of the specific column. In this case, for example, when the values are set like 1, 2, , 4, 5
, the value is put to the 3rd cell. If you want to append the value to the specific column, please modify above script as follows.
From:
let i = 0;
for (i = 0; i < data.length; i++) {
if (!data[i][0]) break;
}
To:
let i = data.length;
If I misunderstood your question and this was not the direction you want, I apologize.
Upvotes: 3