I am trying to integrate google sheets api with nodejs. I am wondering what the correct syntax is for calling two different sheets, separately (note that they are inside one spreadsheet). I tried asking chatgpt and gemini regarding this and I think they gave out to different answers, which adds more confusion. I’ll add them here too, please tell me which of them is correct, or if none, I hope someone could help me with this.
CHATGPT:
async function getData() {
try {
// Fetch data from specific cells/ranges using batchGet
const response = await googleSheets.spreadsheets.values.batchGet({
spreadsheetId,
ranges: [
'RegCred!A1', // Read a single cell from RegCred
'QueueInfo!B2:B5' // Read a range of cells from QueueInfo
],
});
// Extract the data for each range
const regCredData = response.data.valueRanges[0].values;
const queueInfoData = response.data.valueRanges[1].values;
console.log('RegCred Data:', regCredData);
console.log('QueueInfo Data:', queueInfoData);
} catch (error) {
console.error('Error fetching data:', error);
}
}
GEMINI:
const sheets = google.sheets({ version: 'v4' });
async function getSheetData(spreadsheetId, sheetName, range) {
const sheetId = await getSheetIdByName(spreadsheetId, sheetName); // Function to get gid by name (optional)
const res = await sheets.spreadsheets.values.get({
spreadsheetId,
range: `${sheetName}!${range}`,
majorDimension: "ROWS",
});
return res.data.values;
}
// Usage: Assuming spreadsheetId is retrieved elsewhere
const sheet1Data = await getSheetData(spreadsheetId, "Sheet1", "A1:B5");
const sheet2Data = await getSheetData(spreadsheetId, "Sheet2", "C1:D3");
console.log(sheet1Data);
console.log(sheet2Data);
The video tutorials and google sheet api library that I have encountered only uses one sheet as an example, so I am unsure of how exactly I should do this. Also, what I expect is that whenever I use the api call for Sheet1, of course only that sheet will be updated, my main goal is to not make those calls interfere with my other sheet.