Reputation: 143
I am trying to get print the names of all the sheets in a Google Spreadsheet in one column and their respective IDs (part of the URL) in another column. Here is my script so far
function getSchedule() {
var ss=SpreadsheetApp.openById("Sheet_ID");
var sh=ss.getActiveSheet();
var allSheets=ss.getSheets();
var ids=[];
for(var i=0;i<allSheets.length;i++)
{
ids[allSheets[i].getName()]=allSheets[i].getSheetId();
}
var invoicess = SpreadsheetApp.getActiveSpreadsheet();
var schedule = invoicess.getSheetByName("Schedule");
schedule.getRange("A1:B").clear();
var headers = [["Sheet Name", "ID"]];
schedule.getRange("A1:B1").setValues(headers);
for(var d = 1; d=allSheets.length;d++){
schedule.getRange(d+1,1).setValue(allSheets[d]);}
}
So I believe that allSheets should be an array of all the sheet names and ids is an array of the IDs, but the last for loop that I believe should print the values of the allSheets array does not print anything. I would like to have it print starting in cell A2
. I do not have a loop for the IDs yet. Can anyone tell me why nothing is printing in the cells?
Upvotes: 1
Views: 114
Reputation: 27390
ids[allSheets[i].getName()]=allSheets[i].getSheetId();
setValues
instead of setValue
.setValues
to add the header in your file when you can simply add it to the original array in which the data is going to be appended. You don't need for loops to append values with setValues
.function getSchedule() {
const ss=SpreadsheetApp.openById("Sheet_ID");
const invoicess = SpreadsheetApp.getActiveSpreadsheet();
const schedule = invoicess.getSheetByName("Schedule");
const allSheets = ss.getSheets();
const ids = [["Sheet Name", "ID"]];
allSheets.forEach(sh=>{
ids.push([sh.getName(),sh.getSheetId()]);
});
schedule.getRange("A1:B").clear();
schedule.getRange(1,1,ids.length,ids[0].length).setValues(ids);
}
Upvotes: 1
Reputation: 64120
Instead of this ids[allSheets[i].getName()]=allSheets[i].getSheetId();
try this: ids.push([allSheets[i].getName(),allSheets[i].getSheetId()])
and use setValues(ids) at the end.
Upvotes: 0