Make a sheet with its header once
Apps Script recipes › Sheets as a database
setup() creates the tabs the app needs with a bold, frozen header, and adds missing columns to tabs that exist.
File Code.gs
const TABLES = {
Items: ['Id', 'Name', 'Category', 'Stock', 'Created'],
Orders: ['Id', 'Item', 'Qty', 'Customer', 'Created'],
};
function setup() {
const ss = SpreadsheetApp.openById(SHEET_ID);
Object.entries(TABLES).forEach(([name, columns]) => {
const sheet = ss.getSheetByName(name) || ss.insertSheet(name);
const have = sheet.getLastColumn() ? sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0] : [];
const missing = columns.filter(c => !have.includes(c));
if (missing.length) sheet.getRange(1, have.length + 1, 1, missing.length).setValues([missing]);
sheet.getRange(1, 1, 1, sheet.getLastColumn()).setFontWeight('bold');
sheet.setFrozenRows(1);
});
return ss.getUrl();
}
Good to know
- Safe to run again: it never clears data and never makes a tab twice.
Let the AI put it in your appGAS AI Builder knows every recipe here. Describe your app and it uses this code where it fits, in a Google Apps Script project in your own Drive.
Use it in a projectMore in Sheets as a database
Add a row safely when many people save at onceLockService keeps two saves from writing the same row; the row gets an Id and the time it was made.Write many rows at onceBuild a 2-D array and write it with one setValues call instead of one call per cell.A dropdown list from another sheetKeeps the choices in their own tab (Lists) and puts a dropdown on a column that follows that list.Read a sheet as a list of objectsOne getValues() call, the first row as field names, dates turned into text so google.script.run can return them.Update or delete a row by its IdFinds the row by the Id column with TextFinder and writes the changed fields in one setValues call.