Email or CSV only what the filter is showing

TL;DR — Let ops filter the sheet the way they like, then click one menu item to export just the visible rows: a dated CSV in Drive or a short HTML table by email. Built on getVisibleRowObjects, with guards for ‘no filter on’ and huge results.

Ops already know how to slice the sheet: filter Region = East, Status = Overdue, done. What they can’t do is send that view anywhere without copy-pasting into a new file, fixing the formatting, and attaching it by hand.

Give them one menu with two items: Export visible rows to CSV and Email visible rows. The filter is the query, and your script just ships whatever it shows.

TL;DR

  • getVisibleRowObjects(sheet) returns header-keyed rows that aren’t hidden by the filter (or hidden by hand)
  • CSV: visible rows → 2D array → valuesToCsv → a dated file in a Drive folder
  • Email: visible rows → short HTML table (escaped) → send to the person clicking, or a fixed list
  • Guard rails: warn when no filter is on, cap email size, and say how many rows went out
  • Uses the main sheet filter; personal filter views don’t count

This is different from only running the job on the rows you selected. Selection is “these exact rows I clicked.” This is “whatever matches the filter I set,” which is better when the batch is defined by criteria, not by hand.

Using the Apps Script editor a lot? NitroGAS drops free themes & snippets right into script.google.com — optional Co-Pilot when you want a boost.

What not to do

  • Don’t getDataRange().getValues() and hope; it ignores filters completely
  • Don’t email 3,000 rows as an HTML table; send a CSV link instead
  • Don’t drop raw cell values into HTML; escape them, because names and notes contain <, & and quotes
  • Don’t silently export everything when no filter is on; ask first

The menu

function onOpen() { SpreadsheetApp.getUi() .createMenu('Export') .addItem('Visible rows → CSV in Drive', 'exportVisibleRowsToCsv') .addItem('Visible rows → email me', 'emailVisibleRows') .addToUi(); }

Shared first step: get what’s showing

var EXPORT_COLUMNS = ['Client', 'Region', 'Invoice', 'Amount', 'Due', 'Status']; // what leaves the sheet function visibleRowsOrStop_() { var sheet = SpreadsheetApp.getActiveSheet(); var ui = SpreadsheetApp.getUi(); if (!sheet.getFilter()) { var go = ui.alert('No filter is on, so this will export every row on "' + sheet.getName() + '". Continue?', ui.ButtonSet.YES_NO); if (go !== ui.Button.YES) return null; } var rows = getVisibleRowObjects(sheet); // [{ _row, Client, Region, ... }] if (!rows.length) { ui.alert('Nothing is visible with the current filter.'); return null; } return { sheet: sheet, rows: rows }; }

getVisibleRowObjects reads the data once and skips rows where isRowHiddenByFilter or isRowHiddenByUser is true, so manually hidden rows stay out too.

EXPORT_COLUMNS is a deliberate allowlist. Internal notes, costs and margin columns don’t leak just because they’re on the tab.

Option A: CSV in Drive

function exportVisibleRowsToCsv() { var got = visibleRowsOrStop_(); if (!got) return; var ss = SpreadsheetApp.getActive(); var tz = ss.getSpreadsheetTimeZone(); var values = [EXPORT_COLUMNS].concat(got.rows.map(function (r) { return EXPORT_COLUMNS.map(function (c) { var v = r[c]; // Dates as plain yyyy-MM-dd in the sheet's timezone, so Excel and friends don't guess return v instanceof Date ? Utilities.formatDate(v, tz, 'yyyy-MM-dd') : v; }); })); var folder = DriveApp.getFolderById( PropertiesService.getScriptProperties().getProperty('exportsFolderId')); var stamp = Utilities.formatDate(new Date(), tz, 'yyyy-MM-dd_HHmm'); var name = got.sheet.getName() + '_filtered_' + stamp + '.csv'; var file = writeValuesAsCsvToDrive(values, folder, name); SpreadsheetApp.getUi().alert(got.rows.length + ' row(s) exported:\n' + file.getUrl()); }

The timestamp in the name means every export is its own file. Nobody overwrites yesterday’s “East overdue” by accident.

Option B: a short HTML table by email

var EMAIL_MAX_ROWS = 100; function emailVisibleRows() { var got = visibleRowsOrStop_(); if (!got) return; var ui = SpreadsheetApp.getUi(); if (got.rows.length > EMAIL_MAX_ROWS) { ui.alert(got.rows.length + ' rows is too many for an email. Use "Visible rows → CSV in Drive" instead.'); return; } var tz = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); var rows = got.rows.map(function (r) { var o = {}; EXPORT_COLUMNS.forEach(function (c) { o[c] = r[c] instanceof Date ? Utilities.formatDate(r[c], tz, 'yyyy-MM-dd') : r[c]; }); return o; }); // Escaped table from the allowlisted columns var table = htmlTableFromObjects(rows, EXPORT_COLUMNS); var html = fillHtmlTemplate( '<p>{{count}} row(s) from <strong>{{tab}}</strong>, filtered view as of {{when}}.</p>{{{table}}}', { count: rows.length, tab: got.sheet.getName(), when: Utilities.formatDate(new Date(), tz, 'yyyy-MM-dd HH:mm'), table: table // already escaped by htmlTableFromObjects, so raw {{{ }}} is safe here }); var to = Session.getActiveUser().getEmail(); // the person who clicked GmailApp.sendEmail(to, got.sheet.getName() + ' — filtered rows', 'Open in an HTML-capable client.', { htmlBody: html }); SpreadsheetApp.getActive().toast('Emailed ' + rows.length + ' row(s) to ' + to, 'Export', 6); }
  • htmlTableFromObjects builds an escaped <table> from rows and a column list
  • fillHtmlTemplate wraps it with a short intro. {{…}} escapes; triple braces are only for the table we already escaped

Sending to the person who clicked is the safe default: they can forward it. If it should go to a fixed list (a client, a manager), keep that list in a named cell or Script Property, and add a confirmation prompt that shows the recipients before sending.

Filter views vs the filter

isRowHiddenByFilter only knows about the sheet’s main filter. Personal filter views (the ones with their own name and URL) don’t hide rows as far as Apps Script is concerned, so a filter-view user would export everything. Two ways to handle it:

  • Tell ops to use the regular filter (Data → Create a filter) for exports
  • Keep the “No filter is on… continue?” prompt; it catches this case too

Failure modes worth naming

  • Hidden columns: column visibility is ignored; EXPORT_COLUMNS decides what goes out. That’s on purpose.
  • Huge filtered results: the row-by-row visibility check is fine for a few thousand rows. Beyond that, filter in code by the same criteria instead.
  • Session.getActiveUser() comes back blank: this can happen when the person clicking isn’t in the same Workspace domain as the script owner. Fall back to a stored address and say so in the toast.
  • Gmail quota: daily send limits apply. The CSV route doesn’t touch them.
  • Exports folder not shared with the person clicking: they get a link they can’t open. Share the folder with the team.

Soft Co-Pilot note

NitroGAS keeps getVisibleRowObjects, writeValuesAsCsvToDrive, htmlTableFromObjects and fillHtmlTemplate a search away in the editor. Paste your header row and say which columns may leave the sheet, and Co-Pilot can draft both menu items with the allowlist. You still check the first export by eye. Free core; Co-Pilot is a pass you grab when you want the draft.

Closing checklist

  • Visible rows only (getVisibleRowObjects), with a no-filter prompt
  • EXPORT_COLUMNS allowlist decides what leaves the sheet
  • CSV: dated filename in a shared exports folder
  • Email: escaped table, row cap, sent to the clicker by default
  • Team knows filter views don’t count, so use the main filter

Happy Coding!