How to Make Pay Stubs from Google Sheets: One PDF per Employee per Pay Date, with Year-to-Date Totals (2026)

If you pay a handful of people and keep the payroll in a Google Sheet, payday ends with the same chore: someone wants to see how their check was worked out. Typing each stub into a document by hand is slow, and it is where the mistakes creep in: last period’s overtime left in, a deduction missed, a year-to-date figure that no longer matches the sheet. This guide sets up a Payroll tab with one row per employee per pay date, formulas that split each week into regular and overtime hours and work out gross and net pay, checks that flag the usual typos before anyone is paid, and a free Apps Script that turns the rows for a pay date into one PDF earnings statement per employee, with year-to-date totals it adds up itself.

What this guide is not: a tax calculator. The formulas below add up what you enter. Federal, state and local withholding still comes from your payroll provider, your accountant, or the employer tables in IRS Publication 15 and Publication 15-T. If a provider already runs your payroll, its stubs are the official ones; this setup is for employers who pay people from the sheet itself.

What a pay stub should show

Federal law sets the records, not the stub. The Department of Labor’s FLSA Advisor says the Fair Labor Standards Act requires employers to keep accurate records of hours worked and wages paid, but does not require them to give employees pay stubs. Many states do require a written or electronic wage statement each payday, and the list of items differs from state to state, so check your state labor department before you design yours.

The federal records list is a good checklist anyway, because a stub built from it answers most questions. Fact Sheet #21 lists, among other things, hours worked each workweek, the basis of pay and the regular hourly rate, straight-time and overtime earnings, all additions to and deductions from wages, total wages paid each pay period, and the date of payment with the pay period it covers. The stub below shows all of those for the period, plus year-to-date totals.

Leave the full Social Security number off the stub and out of this sheet; the employee ID is enough to tell people apart. Keep personal tax details where your payroll records already live.

Step 1: a Payroll tab, one row per employee per pay date

Name the tab Payroll and freeze the header row (View › Freeze › 1 row). The script finds columns by their header text, so the order is up to you; the formulas below assume this layout:

ColHeaderWhat goes in it
APay dateThe day the wages are paid, formatted as a date (Format › Number › Date)
B, CPeriod start, Period endThe first and last day of the pay period the row covers
DEmployee IDA stable code such as E-101. Year-to-date totals add up rows with the same ID, so a typo in the name doesn’t split anyone’s totals.
EEmployeeFull name, as it should print on the stub
FEmailOptional: where the stub goes if you turn emailing on
G, HWeek 1 hours, Week 2 hoursHours worked in each workweek of the period. For weekly pay, use G and leave H blank.
I, JRegular hours, Overtime hoursFormulas (Step 2)
KRateRegular hourly rate
L, MRegular pay, Overtime payFormulas (Step 2); for a salaried employee, type the period’s salary in L instead
NBonusOptional, blank when there is none
OGross payFormula: the sum of L to N
P to TFederal income tax, Social Security, Medicare, State income tax, Health insuranceThe amounts withheld or deducted this period, as positive numbers. Rename, add or remove deduction columns to match your payroll, then change the DEDUCTIONS list in the script to match.
UNet payFormula: gross pay minus the deductions
VPaymentOptional: “Direct deposit” or “Check 1042”; printed on the stub

Add rows for each pay date below the last one and never overwrite an old row: the earlier rows are what the year-to-date totals are made of. Here is the example data used in the rest of this guide (two employees, two biweekly pay dates; money columns shown without the $ sign):

A
Pay date
B
Period start
C
Period end
D
Employee ID
E
Employee
F
Email
G
Week 1 hours
H
Week 2 hours
I
Regular hours
J
Overtime hours
K
Rate
L
Regular pay
M
Overtime pay
N
Bonus
O
Gross pay
P
Federal income tax
Q
Social Security
R
Medicare
S
State income tax
T
Health insurance
U
Net pay
Nov 6, 2026Oct 19Nov 1E-101Maria Lopezmaria@…423878218.501,443.0055.501,498.5095.0092.9121.7345.0060.001,183.86
Nov 6, 2026Oct 19Nov 1E-102James Chenjames@…364076022.001,672.000.001,672.00120.00103.6624.2450.001,374.10
Nov 20, 2026Nov 2Nov 15E-101Maria Lopezmaria@…444080418.501,480.00111.00100.001,691.00115.00104.8424.5252.0060.001,334.64
Nov 20, 2026Nov 2Nov 15E-102James Chenjames@…404080022.001,760.000.001,760.00130.00109.1225.5254.001,441.36

The tax and insurance amounts in the example are made-up numbers for illustration, not a withholding calculation.

Step 2: hours, overtime, gross and net pay

Federal overtime is counted per workweek. The Department of Labor’s Fact Sheet #23 says covered, non-exempt employees must get at least time and one-half their regular rate for hours over 40 in a workweek, and that averaging hours over two or more weeks is not permitted. So a biweekly row needs each week’s hours separately: Maria’s 42 + 38 hours is 2 hours of overtime, not 80 regular hours. Put these in row 2 and fill them down:

I2, regular hours (at most 40 per week):

=IF(A2="", "", MIN(N(G2), 40) + MIN(N(H2), 40))

J2, overtime hours (anything over 40 in each week):

=IF(A2="", "", MAX(0, N(G2)-40) + MAX(0, N(H2)-40))

N() turns a blank cell into 0, so a weekly row with H left empty still works: 45 hours in G gives 40 regular and 5 overtime.

L2 and M2, regular and overtime pay, rounded to the cent:

=IF(A2="", "", ROUND(I2*K2, 2))
=IF(A2="", "", ROUND(J2*K2*1.5, 2))

O2, gross pay, and U2, net pay:

=IF(A2="", "", SUM(L2:N2))
=IF(A2="", "", O2-SUM(P2:T2))

Round each pay amount with ROUND(…, 2) as shown. Unrounded amounts such as 27.495 add up to a gross that is off by a cent from the stub’s lines, and the script refuses rows like that (see below). If a bonus or commission changes the regular rate, or your state has its own overtime rules (California, for example, also counts overtime by the day), work out those amounts separately and type them in; this layout covers the plain 40-hour rule only.

For a salaried employee, type the salary for the period straight into L (for example the annual salary divided by the number of pay dates in the year) and leave the hours blank. The stub then shows the earnings without an hours column.

Step 3: checks before anyone is paid

A year-to-date column lets you compare each total with last period’s stub at a glance. In W2, filled down, gross pay for the same employee from January 1 up to this pay date (SUMIFS adds a row only when every condition matches):

=IF(A2="", "", SUMIFS($O$2:$O, $D$2:$D, D2, $A$2:$A, ">="&DATE(YEAR(A2), 1, 1), $A$2:$A, "<="&A2))

In the example, Maria’s row for November 20 shows 3,189.50 (1,498.50 + 1,691.00). Swap $O$2:$O for $U$2:$U for year-to-date net pay, or for any deduction column.

Then select A2:V and add these rules with Format › Conditional formatting › Custom formula is:

Custom formulaColorCatches
=AND($A2<>"", COUNTIFS($D$2:$D, $D2, $A$2:$A, $A2)>1)RedThe same employee twice on one pay date: a pasted-twice row would double their pay and their year-to-date totals
=AND($A2<>"", $U2<0)RedDeductions bigger than gross pay
=AND($A2<>"", $C2<>"", $A2<$C2)AmberA pay date before the pay period ends: usually a typo in one of the dates
=AND($B2<>"", $C2<>"", $B2>$C2)AmberA period that ends before it starts

Once the formulas work, protect columns I, J, L, M, O and U with Data › Protect sheets and ranges, so a stray keystroke can’t replace a formula with a number that the next fill-down then hides.

Step 4: the script (one PDF per employee per pay date)

Create a Drive folder for the stubs, keep it private, and copy its ID (the part of the folder’s URL after /folders/). Open Extensions › Apps Script, paste the script below, and set FOLDER_ID, COMPANY_NAME, COMPANY_LINES and QUESTIONS_TO. If your earnings or deduction columns have other headers than the example, change the EARNINGS and DEDUCTIONS lists to match them exactly. Then:

  1. Reload the spreadsheet and run Payroll › Make pay stubs, approving the permissions the first time. PREVIEW is true, so it makes at most 3 PDFs named “PREVIEW ...”, emails nobody and writes nothing back. With PAY_DATE left blank it uses the latest pay date up to today.
  2. Open the previews and check them against the sheet: hours, rates, each line, gross, net and the year-to-date column. Delete them when you’re happy.
  3. Set PREVIEW = false, save and run it again. It makes one PDF per employee for that pay date and adds two columns at the end of the tab, Stub (the PDF link) and Stub made at. If there are more than MAX_PER_RUN (25), run it again; rows with a Stub link are skipped.
// Pay stubs (earnings statements) from a Google Sheets payroll register: one PDF per employee
// per pay date, with hours, rates, each earning and deduction, gross and net pay, and
// year-to-date totals the script adds up from the earlier rows of the same calendar year.
// Sheet: a Payroll tab with a header row, one row per employee per pay date. Required headers:
// Pay date, Employee, Gross pay, Net pay. Optional: Period start, Period end, Employee ID, Email,
// Payment, Rate, the hours columns in HOURS_FOR, and the columns listed in EARNINGS and DEDUCTIONS.
// The script never changes your numbers. It only adds two columns of its own: Stub and Stub made at.
const FOLDER_ID = 'PASTE_DRIVE_FOLDER_ID';      // Drive folder for the PDFs (share it with nobody)
const PAYROLL_SHEET = 'Payroll';
const PAY_DATE = '';                              // '' = the latest pay date up to today, or e.g. '2026-11-20'
const COMPANY_NAME = 'Your company name';
const COMPANY_LINES = ['Street address', 'City, State ZIP'];   // printed under the name
const QUESTIONS_TO = 'payroll@yourcompany.example';            // printed at the bottom of each stub
const EARNINGS = ['Regular pay', 'Overtime pay', 'Bonus'];     // column headers, in print order
const DEDUCTIONS = ['Federal income tax', 'Social Security', 'Medicare', 'State income tax', 'Health insurance'];
const HOURS_FOR = { 'Regular pay': 'Regular hours', 'Overtime pay': 'Overtime hours' };
const RATE_FOR = { 'Regular pay': 1, 'Overtime pay': 1.5 };    // times the Rate column
const CURRENCY = '$';
const EMAIL_STUBS = false;                       // true = email each PDF to the row's Email
const PREVIEW = true;                            // true = at most 3 PDFs named "PREVIEW ...", emails only to you, nothing written back
const REPLY_TO = '';                             // optional reply-to address for the emails
const MAX_PER_RUN = 25;                          // run again to continue; rows with a Stub link are skipped
const MAX_MINUTES = 4.5;                         // stop before Apps Script's 6-minute limit
const KEEP_DOCS = false;                         // false = keep only the PDF, not the Google Doc
const DAY = 86400000;
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
  'October', 'November', 'December'];

function onOpen() {
  SpreadsheetApp.getUi().createMenu('Payroll')
    .addItem('Make pay stubs', 'makePayStubs')
    .addToUi();
}

function makePayStubs(now) {
  let ui = null;
  if (!(now instanceof Date)) {          // run from the menu or a trigger
    now = new Date();
    try { ui = SpreadsheetApp.getUi(); } catch (e) { ui = null; }   // no UI when a trigger runs it
  }
  const lock = LockService.getDocumentLock();
  if (!lock.tryLock(30000)) return;      // another run is still busy
  try {
    const result = run_(now, Date.now());
    if (ui) ui.alert(summary_(result));
    return result;
  } finally {
    lock.releaseLock();
  }
}

function run_(now, startedMs) {
  const ss = SpreadsheetApp.getActive();
  const tz = ss.getSpreadsheetTimeZone();
  const today = dayNum_(Utilities.formatDate(now, tz, 'yyyy-MM-dd'));
  const sheet = ss.getSheetByName(PAYROLL_SHEET);
  if (!sheet) throw new Error('No tab named ' + PAYROLL_SHEET + '.');
  const values = sheet.getDataRange().getValues();
  const reg = readPayroll_(values, tz);
  let payDay = null;
  if (PAY_DATE) {
    payDay = dayNum_(PAY_DATE);
    if (payDay === null) throw new Error('PAY_DATE must look like 2026-11-20.');
  } else {
    reg.rows.concat(reg.bad).forEach(function (r) { if (r.day !== null && r.day <= today && (payDay === null || r.day > payDay)) payDay = r.day; });
  }
  const res = { preview: PREVIEW, payDate: payDay, made: 0, emailed: 0, alreadyDone: 0, left: 0, quota: false, timeUp: false,
    noEmail: [], held: [], skippedRows: reg.skipped, pdfs: [] };
  if (payDay === null) return res;
  const dup = {};
  reg.rows.forEach(function (r) { const k = r.key + '|' + r.day; dup[k] = (dup[k] || 0) + 1; });
  const todo = [];
  reg.rows.forEach(function (r) {
    if (r.day !== payDay) return;
    if (dup[r.key + '|' + r.day] > 1) { res.held.push(r.name + ' (row ' + r.row + '): two or more rows for this pay date, fix them first'); return; }
    const badEarlier = reg.bad.filter(function (b) { return b.key === r.key && b.day !== null && year_(b.day) === year_(r.day) && b.day <= r.day; });
    if (badEarlier.length) { res.held.push(r.name + ' (row ' + r.row + '): fix row ' + badEarlier.map(function (b) { return b.row; }).join(', ') + ' first, the year-to-date totals need it'); return; }
    if (!PREVIEW && r.done) { res.alreadyDone++; return; }
    todo.push(r);
  });
  if (!todo.length) return res;
  let cols = null;                        // Stub / Stub made at, added if missing
  const folder = DriveApp.getFolderById(FOLDER_ID);
  const me = Session.getEffectiveUser().getEmail();
  const limit = PREVIEW ? Math.min(3, MAX_PER_RUN) : MAX_PER_RUN;
  for (let i = 0; i < todo.length; i++) {
    const r = todo[i];
    if (res.made >= limit) { res.left = todo.length - i; break; }
    if (Date.now() - startedMs > MAX_MINUTES * 60000) { res.left = todo.length - i; res.timeUp = true; break; }
    const ytd = ytd_(r, reg.rows);
    const emails = EMAIL_STUBS ? emails_(r.email) : null;
    const to = emails ? (PREVIEW ? [me] : emails) : [];
    if (to.length && MailApp.getRemainingDailyQuota() < to.length) {
      res.left = todo.length - i; res.quota = true; break;     // the next run continues here
    }
    const made = makePdf_(folder, r, ytd, PREVIEW ? 'PREVIEW ' : '');
    res.made++;
    res.pdfs.push(made.url);
    if (EMAIL_STUBS && !emails) res.noEmail.push(r.name + ' (row ' + r.row + ')');
    if (to.length) {
      MailApp.sendEmail(mail_(r, made.blob, to, emails));
      res.emailed++;
    }
    if (!PREVIEW) {
      if (!cols) cols = outputColumns_(sheet, values[0]);
      sheet.getRange(r.row, cols.stub + 1).setValue(made.url);
      sheet.getRange(r.row, cols.madeAt + 1).setValue(Utilities.formatDate(now, tz, 'yyyy-MM-dd HH:mm') +
        (to.length ? ', emailed to ' + emails.join(', ') : ''));
      SpreadsheetApp.flush();              // the link survives even if a later stub fails
    }
  }
  return res;
}

function readPayroll_(values, tz) {
  const col = finder_(values[0]);
  const c = { date: col('Pay date'), start: col('Period start'), end: col('Period end'), id: col('Employee ID'),
    name: col('Employee'), email: col('Email'), payment: col('Payment'), rate: col('Rate'),
    gross: col('Gross pay'), net: col('Net pay'), stub: col('Stub') };
  if (c.date < 0 || c.name < 0 || c.gross < 0 || c.net < 0) {
    throw new Error('The ' + PAYROLL_SHEET + ' tab needs Pay date, Employee, Gross pay and Net pay columns in its first row.');
  }
  const ecol = EARNINGS.map(function (h) { return col(h); });
  const dcol = DEDUCTIONS.map(function (h) { return col(h); });
  const hcol = EARNINGS.map(function (h) { return HOURS_FOR[h] ? col(HOURS_FOR[h]) : -1; });
  const missing = EARNINGS.concat(DEDUCTIONS).filter(function (h) { return col(h) < 0; });
  if (missing.length) throw new Error('Missing column(s) on ' + PAYROLL_SHEET + ': ' + missing.join(', ') + '. Add them or remove them from EARNINGS / DEDUCTIONS.');
  const rows = [], bad = [], skipped = [];
  for (let i = 1; i < values.length; i++) {
    const v = values[i], n = i + 1;
    const get = function (k) { return k < 0 || v[k] == null ? '' : v[k]; };
    const name = String(get(c.name)).trim();
    if (!name && String(get(c.date)).trim() === '' && String(get(c.gross)).trim() === '') continue;   // empty row
    const day = toDay_(get(c.date), tz);
    const key = norm_(get(c.id)) || norm_(name);
    const fail = function (why) { skipped.push('Row ' + n + (name ? ' (' + name + ')' : '') + ': ' + why); bad.push({ row: n, key: key, day: day }); };
    if (day === null) { fail('Pay date is not a date'); continue; }
    if (!name) { fail('no employee name'); continue; }
    const earn = ecol.map(function (k) { return cents_(get(k)); });
    const ded = dcol.map(function (k) { return cents_(get(k)); });
    const hours = hcol.map(function (k) { const h = String(get(k)).trim() === '' ? 0 : number_(get(k)); return h; });
    const gross = cents_(get(c.gross)), net = cents_(get(c.net));
    const rateText = String(get(c.rate)).trim();
    const rate = rateText === '' ? null : number_(get(c.rate));
    if (earn.concat(ded, [gross, net]).some(isNaN) || hours.some(isNaN) || (rate !== null && isNaN(rate))) { fail('a money, hours or Rate cell is not a number'); continue; }
    if (ded.some(function (x) { return x < 0; }) || hours.some(function (x) { return x < 0; })) { fail('a deduction or hours cell is negative'); continue; }
    const sumE = earn.reduce(function (s, x) { return s + x; }, 0), sumD = ded.reduce(function (s, x) { return s + x; }, 0);
    if (sumE !== gross) { fail('Gross pay ' + money_(gross) + ' is not the sum of the earnings columns (' + money_(sumE) + ')'); continue; }
    if (gross - sumD !== net) { fail('Net pay ' + money_(net) + ' is not Gross pay minus the deductions (' + money_(gross - sumD) + ')'); continue; }
    if (net < 0) { fail('Net pay is negative'); continue; }
    const start = String(get(c.start)).trim() === '' ? null : toDay_(get(c.start), tz);
    const end = String(get(c.end)).trim() === '' ? null : toDay_(get(c.end), tz);
    if ((String(get(c.start)).trim() !== '' && start === null) || (String(get(c.end)).trim() !== '' && end === null)) { fail('Period start or Period end is not a date'); continue; }
    if (start !== null && end !== null && start > end) { fail('Period start is after Period end'); continue; }
    rows.push({ row: n, day: day, key: key, id: String(get(c.id)).trim(), name: name, email: String(get(c.email)).trim(),
      payment: String(get(c.payment)).trim(), rate: rate, start: start, end: end, earn: earn, ded: ded, hours: hours,
      gross: gross, net: net, done: String(get(c.stub)).trim() !== '' });
  }
  return { rows: rows, bad: bad, skipped: skipped };
}

// Year to date = this employee's rows with a pay date in the same calendar year, up to and including this one.
function ytd_(r, rows) {
  const mine = rows.filter(function (x) { return x.key === r.key && year_(x.day) === year_(r.day) && x.day <= r.day; });
  const add = function (f) { return mine.reduce(function (s, x) { return s + f(x); }, 0); };
  return { earn: EARNINGS.map(function (h, i) { return add(function (x) { return x.earn[i]; }); }),
    ded: DEDUCTIONS.map(function (h, i) { return add(function (x) { return x.ded[i]; }); }),
    hours: EARNINGS.map(function (h, i) { return add(function (x) { return Math.round(x.hours[i] * 100); }); }),
    gross: add(function (x) { return x.gross; }), net: add(function (x) { return x.net; }) };
}

function outputColumns_(sheet, header) {
  const h = (header || []).map(function (x) { return String(x).trim().toLowerCase(); });
  let width = h.length;
  while (width > 0 && h[width - 1] === '') width--;
  const out = {};
  [['stub', 'Stub'], ['madeAt', 'Stub made at']].forEach(function (p) {
    let i = h.indexOf(p[1].toLowerCase());
    if (i < 0) { i = width++; sheet.getRange(1, i + 1).setValue(p[1]); }
    out[p[0]] = i;
  });
  return out;
}

function makePdf_(folder, r, ytd, prefix) {
  const name = prefix + 'Pay stub - ' + iso_(r.day) + ' - ' + r.name.replace(/[\\\/:*?"<>|]/g, '-') +
    (r.id ? ' (' + r.id.replace(/[\\\/:*?"<>|]/g, '-') + ')' : '');
  const old = folder.getFilesByName(name + '.pdf');
  while (old.hasNext()) old.next().setTrashed(true);   // a re-made stub replaces the old PDF
  const doc = DocumentApp.create(name);
  const file = DriveApp.getFileById(doc.getId());
  file.moveTo(folder);
  render_(doc.getBody(), r, ytd);
  doc.saveAndClose();
  const blob = file.getAs('application/pdf').setName(name + '.pdf');
  const pdf = folder.createFile(blob);
  if (!KEEP_DOCS) file.setTrashed(true);
  return { name: name, blob: blob, url: pdf.getUrl() };
}

function render_(body, r, ytd) {
  const H = DocumentApp.ParagraphHeading;
  body.setMarginTop(54).setMarginBottom(54).setMarginLeft(54).setMarginRight(54);
  const first = body.getParagraphs()[0];
  first.setText(COMPANY_NAME);
  first.setHeading(H.HEADING1);
  COMPANY_LINES.forEach(function (line) { body.appendParagraph(line).setHeading(H.NORMAL); });
  body.appendParagraph('Earnings statement').setHeading(H.HEADING2);
  const info = [['Employee', r.name]];
  if (r.id) info.push(['Employee ID', r.id]);
  info.push(['Pay date', show_(r.day)]);
  if (r.start !== null || r.end !== null) info.push(['Pay period', (r.start !== null ? show_(r.start) : '') + ' to ' + (r.end !== null ? show_(r.end) : '')]);
  if (r.payment) info.push(['Payment', r.payment]);
  body.appendTable(info);
  body.appendParagraph('Earnings').setHeading(H.HEADING3);
  const showHours = EARNINGS.some(function (h, i) { return HOURS_FOR[h] && (r.hours[i] || ytd.hours[i]); });
  const er = [showHours ? ['Earnings', 'Hours', 'Rate', 'This period', 'Year to date'] : ['Earnings', 'This period', 'Year to date']];
  EARNINGS.forEach(function (h, i) {
    if (!r.earn[i] && !ytd.earn[i]) return;            // nothing this year: leave the line off
    if (!showHours) { er.push([h, money_(r.earn[i]), money_(ytd.earn[i])]); return; }
    const hasHours = HOURS_FOR[h] && r.hours[i];
    const rate = hasHours && r.rate !== null && RATE_FOR[h] ? money_(Math.round(r.rate * RATE_FOR[h] * 10000) / 100, 4) : '';
    er.push([h, hasHours ? hrs_(Math.round(r.hours[i] * 100)) : '', rate, money_(r.earn[i]), money_(ytd.earn[i])]);
  });
  er.push(showHours ? ['Gross pay', '', '', money_(r.gross), money_(ytd.gross)] : ['Gross pay', money_(r.gross), money_(ytd.gross)]);
  table_(body, er, showHours ? [1, 2, 3, 4] : [1, 2]).getRow(er.length - 1).editAsText().setBold(true);
  body.appendParagraph('Deductions').setHeading(H.HEADING3);
  const dr = [['Deductions', 'This period', 'Year to date']];
  let curD = 0, ytdD = 0;
  DEDUCTIONS.forEach(function (h, i) {
    curD += r.ded[i]; ytdD += ytd.ded[i];
    if (!r.ded[i] && !ytd.ded[i]) return;
    dr.push([h, money_(r.ded[i]), money_(ytd.ded[i])]);
  });
  dr.push(['Total deductions', money_(curD), money_(ytdD)]);
  table_(body, dr, [1, 2]).getRow(dr.length - 1).editAsText().setBold(true);
  body.appendParagraph('Net pay').setHeading(H.HEADING3);
  const nr = [['', 'This period', 'Year to date'], ['Net pay', money_(r.net), money_(ytd.net)]];
  table_(body, nr, [1, 2]).getRow(1).editAsText().setBold(true);
  body.appendParagraph('Year to date covers pay dates from January 1 to ' + show_(r.day) + '.').setHeading(H.NORMAL);
  if (QUESTIONS_TO) body.appendParagraph('Questions about this statement: ' + QUESTIONS_TO).setHeading(H.NORMAL);
}

function table_(body, cells, rightCols) {
  const t = body.appendTable(cells);
  t.getRow(0).editAsText().setBold(true);
  for (let r = 0; r < cells.length; r++) {
    rightCols.forEach(function (c) {
      t.getCell(r, c).getChild(0).asParagraph().setAlignment(DocumentApp.HorizontalAlignment.RIGHT);
    });
  }
  return t;
}

// The email says nothing about the amounts: they are only in the attached PDF.
function mail_(r, blob, to, emails) {
  const m = {
    to: to.join(','),
    subject: (PREVIEW ? '[PREVIEW to ' + emails.join(', ') + '] ' : '') + 'Your pay stub for ' + show_(r.day),
    body: 'Hello ' + r.name + ',\n\nYour pay stub for the ' + show_(r.day) + ' pay date is attached. ' +
      'If anything on it looks wrong, reply to this email' + (QUESTIONS_TO ? ' or write to ' + QUESTIONS_TO : '') + '.\n\n' + COMPANY_NAME,
    name: COMPANY_NAME,
    attachments: [blob]
  };
  if (REPLY_TO) m.replyTo = REPLY_TO;
  return m;
}

function summary_(r) {
  if (r.payDate === null) return 'No pay date found up to today on the ' + PAYROLL_SHEET + ' tab.' +
    (r.skippedRows.length ? '\n\nRows skipped:\n' + r.skippedRows.slice(0, 15).join('\n') : '');
  const out = [(r.preview ? 'PREVIEW: ' : '') + r.made + ' pay stub PDF(s) made for the ' + show_(r.payDate) + ' pay date.' +
    (r.emailed ? ' Emailed ' + r.emailed + (r.preview ? ' (to you only).' : '.') : '')];
  if (r.alreadyDone) out.push(r.alreadyDone + ' row(s) already have a stub (clear the Stub cell to make it again).');
  if (r.left) out.push(r.left + ' stub(s) left' + (r.quota ? ' (daily email quota reached)' : r.timeUp ? ' (time limit)' : '') + '. Run it again to continue.');
  if (r.held.length) out.push('Not made, check these first:\n' + r.held.join('\n'));
  if (r.noEmail.length) out.push('No valid Email, PDF made but not sent: ' + r.noEmail.join(', '));
  if (r.skippedRows.length) out.push('Rows skipped:\n' + r.skippedRows.slice(0, 15).join('\n') +
    (r.skippedRows.length > 15 ? '\n...and ' + (r.skippedRows.length - 15) + ' more' : ''));
  return out.join('\n\n');
}

// ---- small helpers ----
function finder_(header) {
  const h = (header || []).map(function (x) { return String(x).trim().toLowerCase(); });
  return function (name) { return h.indexOf(name.toLowerCase()); };
}

function norm_(s) {
  return String(s || '').trim().replace(/\s+/g, ' ').toLowerCase();
}

function emails_(s) {
  const list = String(s || '').split(/[,;]/).map(function (x) { return x.trim(); }).filter(String);
  const ok = list.length > 0 && list.every(function (x) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(x); });
  return ok ? list : null;
}

function number_(s) {
  if (typeof s === 'number') return s;
  const t = String(s).replace(/[\s,]/g, '').replace(CURRENCY, '');
  return /^-?\d+(\.\d+)?$/.test(t) ? Number(t) : NaN;
}

// Money is kept in whole cents so 0.1 + 0.2 adds up exactly. A blank cell is 0.
function cents_(s) {
  if (String(s).trim() === '') return 0;
  const n = number_(s);
  return isNaN(n) ? NaN : Math.round(n * 100);
}

function money_(cents, maxDecimals) {
  const neg = cents < 0, a = Math.abs(cents);
  let whole = Math.floor(a / 100), frac = a - whole * 100;
  let dec = (frac / 100).toFixed(maxDecimals || 2).slice(2);
  if (maxDecimals) dec = dec.replace(/0+$/, '').padEnd(2, '0');
  return (neg ? '-' : '') + CURRENCY + String(whole).replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + dec;
}

function toDay_(v, tz) {
  if (v instanceof Date) return isNaN(v.getTime()) ? null : dayNum_(Utilities.formatDate(v, tz, 'yyyy-MM-dd'));
  return typeof v === 'string' ? dayNum_(v.trim()) : null;
}

// Dates are whole days counted from 1970-01-01, so time zones and daylight saving can't shift them.
function dayNum_(s) {
  const m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(String(s));
  if (!m) return null;
  const n = Date.UTC(+m[1], +m[2] - 1, +m[3]) / DAY;
  const back = ymd_(n);
  return back.y === +m[1] && back.m === +m[2] && back.d === +m[3] ? n : null;
}

function ymd_(n) {
  const d = new Date(n * DAY);
  return { y: d.getUTCFullYear(), m: d.getUTCMonth() + 1, d: d.getUTCDate() };
}

function year_(n) {
  return ymd_(n).y;
}

function show_(n) {
  const t = ymd_(n);
  return MONTHS[t.m - 1] + ' ' + t.d + ', ' + t.y;
}

function iso_(n) {
  const t = ymd_(n);
  return t.y + '-' + String(t.m).padStart(2, '0') + '-' + String(t.d).padStart(2, '0');
}

// Hours are kept in hundredths; shown without trailing zeros.
function hrs_(h100) {
  return String(Math.round(h100) / 100);
}

What the script does

Step 5: getting the stubs to employees

Pay stubs are private. Don’t share the folder; share each PDF with its own employee only, or print it and hand it over with the check.

To email them instead, set EMAIL_STUBS = true. Each PDF goes to the row’s Email from your account, with COMPANY_NAME as the sender name; replies go to REPLY_TO if set. The email says only that the stub is attached, with no amounts in the message. Run it with PREVIEW = true first: preview emails come only to you, with the real recipient in the subject. Rows without a valid Email still get a PDF and are listed in the summary. The script checks your remaining daily Apps Script email quota before each email (100 recipients a day on a consumer Gmail account, 1,500 on Google Workspace) and stops when it would run out; the next run carries on. If your state lets employees choose paper stubs, keep a column for who wants paper and print those.

Pitfalls

FAQ

Can Google Sheets make pay stubs?

Yes. Keep one row per employee per pay date on a Payroll tab with the hours, rate, each earning, each deduction, gross pay and net pay. A short Apps Script can then turn each row for a pay date into a PDF earnings statement with year-to-date totals and save it in a Drive folder. The script on this page does that, and it can also email each stub to the employee.

Does Google Sheets calculate payroll taxes?

No. Sheets has no built-in tax tables, and the formulas in this guide don’t calculate withholding. Enter the federal, state and other withholding amounts your payroll provider, accountant or the IRS Publication 15-T method gives you, and let the sheet add up gross pay, deductions, net pay and the year-to-date totals.

How do I calculate overtime for a biweekly pay period in Google Sheets?

Record the hours for each workweek separately, because federal overtime is counted per workweek and hours can’t be averaged over two weeks. With week 1 in G and week 2 in H, regular hours are =MIN(N(G2), 40) + MIN(N(H2), 40) and overtime hours are =MAX(0, N(G2)-40) + MAX(0, N(H2)-40). Overtime pay is then =ROUND(J2*K2*1.5, 2). Some states also have daily overtime rules.

How do I add year-to-date totals to a pay stub in Google Sheets?

Add up the employee’s rows from January 1 to this pay date: =SUMIFS($O$2:$O, $D$2:$D, D2, $A$2:$A, ">="&DATE(YEAR(A2), 1, 1), $A$2:$A, "<="&A2), where O is gross pay, D the employee ID and A the pay date. Use the same pattern for net pay or any deduction. The script on this page works out the same totals for every line on the stub.

Are employers required to give employees pay stubs?

Not under the federal Fair Labor Standards Act: the Department of Labor says the FLSA requires accurate records of hours worked and wages paid but doesn’t require pay stubs. Many states do require a wage statement each payday, and what it must show varies, so check your state labor department.

Can I email pay stubs from Google Sheets?

Yes. In the script on this page set EMAIL_STUBS = true and each PDF is emailed to the address in the row’s Email column. Try it with PREVIEW = true first, which sends every email only to you. The email itself doesn’t mention any amounts; they are only in the attached PDF.

Want documents without maintaining a script? SheetWeave (disclosure: we make it) is a Google Sheets add-on that fills a Google Docs template from each row and saves a Doc, a PDF, or both in a Drive folder you choose, writing the links back to the row. It can run on selected rows, all rows, or only new ones. Sheet data stays inside your Google account and it uses narrow scopes. 14-day free trial, no credit card required.
See SheetWeave

Related Google Sheets guides

Instructions refer to Google Sheets, Google Docs, Google Drive and Apps Script as they worked on November 21, 2026, and to the Department of Labor and IRS pages cited as they stood that day. Not legal, tax or payroll advice, and not affiliated with Google, the Department of Labor or the IRS. Google Sheets, Google Docs and Google Drive are trademarks of Google LLC. Check each stub against your payroll records before you hand it out. Questions or corrections: hello@loomwise.app.