insertRowAtTop(sheet, values, opts) inserts a new row under the header, writes values into it, and copies formatting only from the row that is now immediately below (the previous first data row). {headerRows} defaults to 1. This does not copy formulas.
When to use
- A log or inbox sheet that should show the newest row under the header
- Keeping currency, date, and fill formats when you insert instead of append
- A menu action that adds one row at the top of a table
How to use this snippet
/**
* Insert a row under the header, write values, and copy formatting from
* the row below. opts.headerRows defaults to 1. Formulas are not copied.
* setValues is used for the new row and does not wipe the formats just
* applied. Returns the written range.
*
* @param {GoogleAppsScript.Spreadsheet.Sheet} sheet
* @param {Array} values
* @param {{headerRows?: number}} [opts]
* @return {GoogleAppsScript.Spreadsheet.Range}
*/
function insertRowAtTop(sheet, values, opts) {
opts = opts || {};
if (!sheet) throw new Error('insertRowAtTop: sheet required');
if (!values || !values.length) throw new Error('insertRowAtTop: values required');
var headerRows = opts.headerRows == null ? 1 : Number(opts.headerRows);
if (!(headerRows >= 0) || headerRows !== headerRows || Math.floor(headerRows) !== headerRows) {
throw new Error('insertRowAtTop: headerRows must be an integer >= 0');
}
var insertAt = headerRows + 1;
sheet.insertRowBefore(insertAt);
var lastCol = sheet.getLastColumn();
var width = Math.max(values.length, lastCol, 1);
var dest = sheet.getRange(insertAt, 1, 1, width);
// The previous first data row is now immediately below the new row.
if (sheet.getMaxRows() >= insertAt + 1) {
sheet.getRange(insertAt + 1, 1, 1, width).copyTo(
dest,
SpreadsheetApp.CopyPasteType.PASTE_FORMAT,
false
);
}
sheet.getRange(insertAt, 1, 1, values.length).setValues([values]);
return sheet.getRange(insertAt, 1, 1, values.length);
}
Example
function addNewestTicket(ticket) {
var sheet = SpreadsheetApp.getActive().getSheetByName('Tickets');
insertRowAtTop(sheet, [new Date(), ticket.id, ticket.status], { headerRows: 1 });
}
Notes
- Only formats are copied from the row below (
PASTE_FORMAT). A per-row formula in that row stays on that row; the new row will not get it. Use a headerARRAYFORMULAor a column formula if every new row needs the same calculation, or copy the formula separately. setValuesdoes not clear the formats you just pasted.- Inserting under the header shifts the rows below it. Formula ranges that started at the old first data row can slide and miss the new row — see the notes in the matching guide, and prefer open-ended ranges like
A2:Awhen you mean "all data." headerRows: 0inserts at the very top, above a header. Frozen rows are not changed automatically; keepheaderRowsin sync with how the sheet is frozen.
Happy Coding!
