ReoGrid ReoGrid Web

Collapsible Budget Reports in a JavaScript Spreadsheet — Excel-Style Row Grouping

· unvell team
Collapsible Budget Reports in a JavaScript Spreadsheet — Excel-Style Row Grouping

A budget-vs-actual report has three kinds of reader. The CFO wants the division totals. A department head wants their own department. The person explaining an overspend wants every line. In Excel, one sheet serves all three: Data → Group, and the small 1 2 3 buttons in the corner switch between the views.

Web versions of this report often turn into a tree grid, and the sheet stops being a sheet. ReoGrid Web has Excel’s outline instead. Rows stay rows, subtotals stay formulas, and the grouping is saved in the xlsx file. This article builds a three-level report, then covers the places where outlines catch people out.

Grouping is a Pro feature, and so are the SUM subtotals in this article. The tier section has the details.


The sample: a budget-vs-actual report

Two divisions, two departments each, three expense lines per department, in thousands. Each department has a total row below its lines, each division has a total below its departments, and one company total closes the sheet.

import { createReogrid } from '@reogrid/pro';

const grid = createReogrid({ workspace: '#grid', licenseKey: 'YOUR_LICENSE_KEY' });
const ws = grid.worksheet;

type Line = [item: string, budget: number, actual: number];
const ORG: { name: string; depts: { name: string; lines: Line[] }[] }[] = [
  { name: 'Sales Division', depts: [
    { name: 'East Region', lines: [['Payroll', 4200, 4310], ['Travel', 380, 452], ['Advertising', 620, 575]] },
    { name: 'West Region', lines: [['Payroll', 3600, 3555], ['Travel', 340, 318], ['Advertising', 480, 512]] },
  ] },
  { name: 'Corporate Division', depts: [
    { name: 'General Affairs', lines: [['Payroll', 1900, 1885], ['Supplies', 210, 236], ['Utilities', 340, 329]] },
    { name: 'IT', lines: [['Payroll', 2100, 2140], ['Software', 760, 812], ['Telecom', 290, 274]] },
  ] },
];

const HEAD = { bold: true, backgroundColor: '#1e3a5f', color: '#ffffff' } as const;
const DEPT = { bold: true, backgroundColor: '#eef5ff' } as const;
const DIV  = { bold: true, backgroundColor: '#d6e6fb' } as const;
const ALL  = { bold: true, backgroundColor: '#b4cff2' } as const;

ws.suspendRender();
[190, 90, 90, 90, 80].forEach((w, c) => ws.column(c).setWidth(w));
['Department / item', 'Budget', 'Actual', 'Variance', 'Used'].forEach((h, c) =>
  ws.cell(0, c).setValue(h).setStyle({ ...HEAD, textAlign: c ? 'right' : 'left' }));

// r is a 0-based row index; n is the same row in A1 notation
function writeRow(r: number, label: string, budget: number | string, actual: number | string, style = {}) {
  const n = r + 1;
  ws.cell(r, 0).setValue(label);
  ws.cell(r, 1).setValue(budget);
  ws.cell(r, 2).setValue(actual);
  ws.cell(r, 3).setValue(`=B${n}-C${n}`);
  ws.cell(r, 4).setValue(`=C${n}/B${n}`);
  ws.range(`A${n}:E${n}`).setStyle(style);
}

let r = 1;
const divisionTotals: number[] = [];

for (const div of ORG) {
  const divStart = r;
  const deptTotals: number[] = [];

  for (const dept of div.depts) {
    const deptStart = r;
    for (const [item, budget, actual] of dept.lines) {
      writeRow(r++, `    ${item}`, budget, actual);
    }
    const sum = (c: string) => `=SUM(${c}${deptStart + 1}:${c}${r})`;
    writeRow(r, `  ${dept.name} total`, sum('B'), sum('C'), DEPT);
    ws.groupRows(deptStart, r);          // the lines AND their total row
    deptTotals.push(r++);
  }

  const add = (c: string) => '=' + deptTotals.map((t) => `${c}${t + 1}`).join('+');
  writeRow(r, `${div.name} total`, add('B'), add('C'), DIV);
  ws.groupRows(divStart, r);             // the departments AND the division total
  divisionTotals.push(r++);
}

const grand = (c: string) => '=' + divisionTotals.map((t) => `${c}${t + 1}`).join('+');
writeRow(r, 'Company total', grand('B'), grand('C'), ALL);

ws.range(`B2:C${r + 1}`).setFormat('#,##0');
ws.range(`D2:D${r + 1}`).setFormat('#,##0;[Red](#,##0)');
ws.range(`E2:E${r + 1}`).setFormat('0.0%');
ws.resumeRender();
Result
Every group open. The 1 2 3 buttons are in the corner, and each − button sits on a total row.
Every group open. The 1 2 3 buttons are in the corner, and each − button sits on a total row.

Two things to notice in the loop. The groupRows calls nest by themselves: ReoGrid works out the level from which range contains which, so the order of the calls doesn’t matter. And each range ends on the total row, which is the subject of the next section.


The one rule that differs from Excel

In Excel you select only the detail rows and click Group, and the row after them is treated as the summary. In ReoGrid Web the range includes the summary row. That row stays visible when the group closes, and it carries the button.

// Lines on rows 2–4, total on row 5 (0-based: 1–3 and 4)

// Right: closes down to the total row
ws.groupRows(1, 4);

// Wrong: closes down to row 4, so the last expense line stays on screen
ws.groupRows(1, 3);

Nothing warns you about the second form, because it is a valid group. If a collapsed sheet shows one stray line per group, check this first. When you load a file from Excel, ReoGrid does the translation for you.

Many reports put the total above its lines. Turn that on, and start the range on the total row:

ws.setRowSummaryBelow(false);
ws.groupRows(1, 4);   // total on row 2, lines on rows 3–5

Columns follow the same rule with groupColumns, and setColumnSummaryRight(false) is the counterpart for a total on the left. For months with the quarter total to their right:

ws.groupColumns(1, 4);   // Jan, Feb, Mar in B:D, and the Q1 total in E

Driving the outline from code

Users get the panel without any code: a − or + on each total, and 1 2 3 in the corner. To do the same from your own toolbar, call collapseRowsToLevel. Its argument is zero-based, so it is one less than the number on the button.

ButtonCallWhat this sheet shows
1ws.collapseRowsToLevel(0)Division totals and the company total
2ws.collapseRowsToLevel(1)The department totals as well
3ws.collapseRowsToLevel(2)Every row

The last value is always the number of group levels, which ws.getRowOutlines().getLevelCount() returns.

// <button data-level="0">Divisions</button>
// <button data-level="1">Departments</button>
// <button data-level="2">All lines</button>
document.querySelectorAll<HTMLButtonElement>('button[data-level]').forEach((btn) =>
  btn.addEventListener('click', () => ws.collapseRowsToLevel(Number(btn.dataset.level))));

ws.collapseRowsToLevel(1);   // open at department level
Result
After ws.collapseRowsToLevel(1), the same as pressing 2. The row numbers skip the hidden expense lines, and the totals haven't changed.
After ws.collapseRowsToLevel(1), the same as pressing 2. The row numbers skip the hidden expense lines, and the totals haven't changed.

To open or close a single group, name its level and first row. Levels count from 0 at the outermost, and getGroupsAtLevel lists what is there:

ws.collapseRowOutline(1, 5);   // West Region: level 1, starts on 0-based row 5
ws.expandRowOutline(1, 5);

for (const g of ws.getRowOutlines().getGroupsAtLevel(1)) {
  console.log(g.start, g.count, g.collapsed);
}

Subtotals: SUM, not SUBTOTAL

Collapsing hides rows and changes no values, because SUM counts hidden rows, as it does in Excel. The company total reads 15,220 whichever button is pressed.

The division totals add the department totals (=B5+B9) instead of summing the whole block, which would count every line twice.

Excel users often reach for SUBTOTAL here, since it skips other subtotals inside its range. ReoGrid Web’s formula engine doesn’t have SUBTOTAL. Typing it gives #NAME?, and so does opening an xlsx that contains it, even though the file stores a result for that cell. Excel’s Data → Subtotal command writes exactly these formulas, so check any such file before you bring it in. Where your code generates the sheet, use the pattern above.


Adding a line, and other rules

ws.rows.insertAt keeps groups in step: a row inserted inside a group makes the group longer. The total formula depends on where the row lands.

InsertThe group=SUM(B2:B4)
Between two linesGrowsBecomes =SUM(B2:B5)
Directly above the totalGrowsStays =SUM(B2:B4), so the new line is left out

Directly above the total is the natural place for a new line, so write the total again after inserting:

function addLine(deptStart: number, totalRow: number) {
  ws.rows.insertAt(totalRow);     // the total moves down one row
  const n = totalRow + 2;         // its new A1 row number
  for (const c of ['B', 'C']) {
    ws.cell(`${c}${n}`).setValue(`=SUM(${c}${deptStart + 1}:${c}${n - 1})`);
  }
}

The division and company totals point at total cells, so their references follow the move on their own.

A few more rules:

  • Groups form a tree. Two ranges that partly overlap throw an error: Outline groups must be nested, disjoint, or identical. Nesting goes nine levels deep.
  • ungroupRows needs the exact span of the group. clearRowOutlines() removes them all.
  • Sorting moves values, not groups. Groups are stored as row positions, so sort within one block of lines and don’t sort across total rows.
  • groupRows and the panel’s buttons aren’t on the undo stack. For an undoable group, use grid.actionManager.execute(new GroupRowsAction(1, 4)), with GroupRowsAction imported from @reogrid/pro.

A totals-only PDF

Collapsed rows don’t print. PDF export and browser printing both skip hidden rows, so the outline doubles as a report selector.

import { preloadPdfFont } from '@reogrid/pro';

await preloadPdfFont('ja');                        // once, at app start
ws.collapseRowsToLevel(1);
grid.saveAsPdf({ locale: 'ja', filename: 'budget-summary.pdf' });

Call ws.collapseRowsToLevel(2) first and the same export gives the full detail. The PDF invoices article covers paper size, page breaks and headers.


Saving to xlsx, and loading from Excel

saveAsXlsx() stores the outline the way Excel does: an outline level on each row, a collapsed flag on the summary row, and the summary direction on the sheet. Load that file back and you get the same groups, in the same open or closed state. There’s nothing extra to call.

It works in the other direction too. loadFromFile reads the groups in an Excel file and converts them to ReoGrid’s ranges, summary row included.


Where Lite ends and Pro begins

LitePro
Group, collapse and expand, with the outline panel—✅
Groups in a loaded xlsxIgnored, every row shown✅
Arithmetic totals such as =B5+B9✅✅
SUM and other functions#NAME?✅
saveAsXlsx—✅

In Lite, the grouping methods do nothing except log a console warning.


Wrapping up

An outline lets one sheet serve readers who want different amounts of detail. groupRows builds it from ranges that end on the total row, collapseRowsToLevel switches the view, and the result prints and saves the way it looks. Write subtotals with SUM and addition rather than SUBTOTAL, and rewrite the total after adding a line directly above it.

Try it in the outline demo, which groups rows and columns together, and see the grouping docs for the rest of the API. If the sheet goes round for sign-off first, the cell comments article covers the review step.

Try ReoGrid Web in your project

Canvas-based Excel-compatible spreadsheet component for React and Vue. Lite is free — start with one npm install.

Related articles

Stay Updated

Be first to know — get updates as they ship

Get notified of new releases, features, and announcements.
No spam — just updates that matter.