Created
June 21, 2023 15:56
-
-
Save marksowell/f6ed97a3faacd24ee784226113c67142 to your computer and use it in GitHub Desktop.
Google Apps Script to Create a Table of Contents in Google Sheets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createTOC() { | |
var ss = SpreadsheetApp.getActiveSpreadsheet(); | |
var sheets = ss.getSheets(); | |
// Create a new sheet called "TOC" or set it as the first sheet | |
var sheet = ss.getSheetByName("TOC") || ss.insertSheet("TOC", 0); | |
sheet.clear(); // Clear the TOC sheet | |
if(sheet.getMaxColumns() > 1){ | |
sheet.hideColumns(2, sheet.getMaxColumns() - 1); | |
} | |
// Set the header for the TOC | |
var header = sheet.getRange("A1").setValue("Sheet Name"); | |
header.setFontWeight("bold"); | |
header.setFontSize(10); | |
header.setFontColor("#FFFFFF"); | |
header.setBackground("#434343"); | |
sheet.setColumnWidth(1, 300); | |
// Loop through all sheets and write their names and URLs to the TOC | |
for(var i = 0; i < sheets.length; i++) { | |
var name = sheets[i].getName(); | |
// Skip the TOC itself | |
if(name !== "TOC") { | |
var url = ss.getUrl() + "#gid=" + sheets[i].getSheetId(); | |
// Create the hyperlink in the cell | |
var cell = sheet.getRange(i+1, 1); | |
cell.setFormula('=HYPERLINK("' + url + '","' + name + '")'); | |
// Alternate row color | |
if ((i+1) % 2 == 0) { | |
cell.setBackground("#efefef"); | |
} else { | |
cell.setBackground("#FFFFFF"); | |
} | |
} | |
} | |
// Hide all rows beyond the last sheet | |
var lastRow = sheets.length + 1; // Considering the header row | |
if(sheet.getMaxRows() > lastRow){ | |
sheet.hideRows(lastRow, sheet.getMaxRows() - lastRow); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment