Suite Utils
Back to blog
NetSuite TipsOct 12, 2026 • 9 min read

Build Custom Financial Statements with NetSuite

Custom Financials: Build Multi-Tab Workbooks with NetSuite Suitelets, Automate Validation & Delivery.

Suite UtilsHow we write these guides
Build Custom Financial Statements with NetSuite
On this page

Your controller needs a monthly financial package across twelve golf course departments by Tuesday. NSPB quoted 150 development hours and still couldn't handle the combined-department rollups your clients require. Standard Financial Report Builder forces you to choose: either one massive consolidated statement or dozens of individual reports you stitch together manually in Excel. Suitelets let you build exactly what the business needs, multi-tab workbooks with department-level income statements, combined rollups, automated validation checks, and password-protected PDF delivery, all triggered from a single button in the UI.

The Problem: When Native Tools Hit the Wall

NetSuite's Financial Report Builder excels at GAAP-compliant statements with standard row/column logic. It falls apart when you need:

  • Department-level tabs, one worksheet per location (Green Fees, Pro Shop, F&B, Grounds) with shared header/footer formatting
  • Custom rollups, "Golf Shop" combining Green Fees + Pro Shop with eliminations
  • Cross-statement validation, automatic checks that balance sheet ties to income statement, cash flow reconciles, intercompany nets to zero
  • Client-ready output, hide workpaper tabs, password protect, generate PDF in one click

Saved Searches can pull the data but can't produce formatted Excel. Workbooks pivot well but lack the multi-tab workbook structure and programmatic finalization. The Suitelet approach owns the entire pipeline: data retrieval → Excel generation → validation → delivery.

Architecture: Suitelet as Report Engine

A production-grade reporting Suitelet runs in three phases:

PhaseNetSuite APIsGovernance Cost
Parameter collection & validationN/ui/serverWidget, N/runtime~50 units
Data aggregationN/search (Saved Search or SuiteQL)10–500 units depending on volume
File generation & responsefile handling and N/task~200 units

The critical decision: run synchronously or delegate to Map/Reduce. For packages under 5,000 rows, a single Suitelet execution stays under the 1,000 governance unit limit. Beyond that, spawn a Map/Reduce script via task.create({ taskType: task.TaskType.MAP_REDUCE }) and email the file when complete. Suitelets are capped at 1,000 usage units per execution, the same ceiling as User Event and Portlet scripts, while Map/Reduce scripts get 10,000 units per phase with no overall limit.

Building the Generator: Step-by-Step

1. Create the Suitelet Entry Point

/**
 * @NApiVersion 2.1
 * @NScriptType Suitelet
 */
define(['N/ui/serverWidget', 'N/search', 'N/file', 'N/runtime', 'N/log', 'N/task'],
    (serverWidget, search, file, runtime, log, task) => {

    const onRequest = (context) => {
        if (context.request.method === 'GET') {
            return renderForm(context);
        }
        return generateReport(context);
    };

    const renderForm = (context) => {
        const form = serverWidget.createForm({ title: 'Financial Statement Generator' });
        form.clientScriptModulePath = './cs_financial_generator.js';

        // Department multi-select
        form.addField({
            id: 'custpage_departments',
            type: serverWidget.FieldType.MULTISELECT,
            label: 'Departments (Individual Tabs)',
            source: 'department'
        });

        // Combined rollup definition
        form.addField({
            id: 'custpage_rollups',
            type: serverWidget.FieldType.TEXTAREA,
            label: 'Combined Rollups (JSON)',
            help: 'e.g., {"Golf Shop": ["1", "2"], "F&B": ["3", "4"]}'
        });

        // Period selector
        form.addField({
            id: 'custpage_period',
            type: serverWidget.FieldType.SELECT,
            label: 'Posting Period',
            source: 'accountingperiod'
        }).isMandatory = true;

        // Prior month file for template carry-forward
        form.addField({
            id: 'custpage_prior_file',
            type: serverWidget.FieldType.FILE,
            label: 'Prior Month Workbook (Optional)'
        });

        form.addSubmitButton({ label: 'Generate Workbook' });
        form.addButton({ id: 'custpage_finalize', label: 'Finalize & Protect', functionName: 'finalizeWorkbook' });

        context.response.writePage(form);
    };

    return { onRequest };
});

2. Pull Financial Data with SuiteQL

Avoid N/search for complex multi-join financial queries. SuiteQL on the transaction and account tables gives you precise control over grouping. Use the N/query module's runSuiteQL method, it returns results as plain objects, no ResultSet boilerplate.

const getFinancialData = (periodId, departmentIds) => {
    const query = `
        SELECT
            a.acctnumber AS account_number,
            a.acctname AS account_name,
            a.accttype AS account_type,
            d.name AS department,
            SUM(tl.debitamount - tl.creditamount) AS amount
        FROM transaction t
        JOIN transactionline tl ON tl.transaction = t.id
        JOIN account a ON a.id = tl.account
        LEFT JOIN department d ON d.id = tl.department
        WHERE t.postingperiod = ?
          AND t.type IN ('Journal', 'VendBill', 'CustInvc', 'CustPymt', 'VendPymt')
          AND a.accttype IN ('Income', 'Expense', 'COGS', 'Other Income', 'Other Expense')
          ${departmentIds.length ? `AND tl.department IN (${departmentIds.map(() => '?').join(',')})` : ''}
        GROUP BY a.acctnumber, a.acctname, a.accttype, d.name
        ORDER BY a.acctnumber, d.name
    `;

    const params = [periodId, ...departmentIds];
    return query.runSuiteQL({ params }).asMappedResults();
};

The accttype filter excludes balance sheet accounts from the income statement tabs. Run a separate query for balance sheet if your package needs it.

3. Generate the Excel Workbook

NetSuite's N/render module only outputs PDF, it has no native XLSX generation capability. For multi-tab Excel, build an Office Open XML (XLSX) file manually. It's a zip of XML files, but you only need xl/workbook.xml and one xl/worksheets/sheetN.xml per tab. External npm packages don't run in SuiteScript; write the XML yourself or use a lightweight builder.

const buildWorkbook = (dataByDept, rollups, priorWorkbook) => {
    const sheets = [];
    let sheetIndex = 1;

    // Individual department tabs
    for (const [deptId, rows] of Object.entries(dataByDept)) {
        sheets.push({
            name: `IS_${deptId}`.substring(0, 31),
            data: formatIncomeStatement(rows),
            id: sheetIndex++
        });
    }

    // Combined rollup tabs
    for (const [rollupName, deptIds] of Object.entries(rollups)) {
        const combined = deptIds.flatMap(id => dataByDept[id] || []);
        sheets.push({
            name: `IS_${rollupName}`.substring(0, 31),
            data: formatIncomeStatement(combined),
            id: sheetIndex++
        });
    }

    // Checks tab — validation formulas
    sheets.push({
        name: 'Checks',
        data: buildValidationRows(dataByDept, rollups),
        id: sheetIndex
    });

    return createXLSX(sheets, priorWorkbook);
};

Key implementation details:

  • Sheet names truncated to 31 characters (Excel limit)
  • Prior workbook parsing, read xl/worksheets/sheetN.xml from the uploaded file to preserve column widths, hidden rows, and user-entered formulas
  • Number formatting, apply numFmtId: 4 (#,##0.00) to amount columns; store raw numbers in cells, let Excel render
  • Header rows, freeze pane at row 5, repeat on each printed page via pageSetup

4. The Validation Layer: Automated Checks Tab

This is where the Suitelet pays for itself. The Checks tab runs formulas that would take an accountant hours to verify manually:

CheckFormula LogicPass Condition
BS/IS Tie=BS!NetIncome - IS!NetIncome0
Cash Flow Reconcile=CF!EndCash - BS!Cash0
Intercompany NetSUMIF(IC_Account, "<>0")0
Department RollupRollup_Total - SUM(Individual_Depts)0
Prior Period MatchCurrent_BegBal - Prior_EndBal0
const buildValidationRows = (dataByDept, rollups) => {
    const rows = [
        ['Check Name', 'Formula', 'Result', 'Status'],
        ['BS/IS Net Income Tie', '=BS!C100 - IS_Total!C100', null, '=IF(C2=0,"PASS","FAIL")'],
        ['Cash Flow Reconciliation', '=CF!C50 - BS!C10', null, '=IF(C3=0,"PASS","FAIL")'],
        ['Intercompany Eliminations Net Zero', '=SUMIF(IC_Map!B:B,"<>0",IC_Map!C:C)', null, '=IF(C4=0,"PASS","FAIL")']
    ];

    // Department rollup validation
    for (const [rollupName, deptIds] of Object.entries(rollups)) {
        const deptRefs = deptIds.map(id => `'IS_${id}'!C100`).join('+');
        rows.push([
            `Rollup: ${rollupName}`,
            `='IS_${rollupName}'!C100 - (${deptRefs})`,
            null,
            `=IF(C${rows.length+1}=0,"PASS","FAIL")`
        ]);
    }

    return rows;
};

When the accountant opens the workbook, Excel calculates instantly. Red "FAIL" flags jump out. No manual tick-marks.

Finalize: Hide, Protect, PDF

The "Finalize" button triggers a second Suitelet call (or a client-script POST) that:

  1. Loads the generated file from the File Cabinet (file.load({ id: fileId }))
  2. Hides workpaper tabs, set state="hidden" in xl/workbook.xml for Checks, raw data sheets, and any helper tabs
  3. Applies workbook password, Office Open XML encryption requires AES-256; SuiteScript has no native crypto for this. Two practical paths:
  • Option A: Call an external microservice (AWS Lambda, Cloudflare Worker) via an external call that takes the XLSX bytes, encrypts with libreoffice --headless --convert-to xlsx:"Calc MS Excel 2007 XML" --password "pwd", returns protected file
  • Option B: Skip encryption, rely on NetSuite file cabinet permissions (role-based access) and deliver via a password-protected download link (generate a one-time token, store in custom record, expire after 24 hrs)
  1. Generates PDF, use render.xmlToPdf on a separate XML template per visible tab, then merge externally (SuiteScript cannot merge PDFs natively)
  2. Saves both files to the client's folder in the File Cabinet, emails the controller
const finalizeWorkbook = (fileId, password) => {
    const workbookFile = file.load({ id: fileId });
    const xml = workbookFile.getContents();

    // Hide tabs: parse workbook.xml, set sheet state="hidden" for non-deliverable sheets
    const hiddenXml = hideSheets(xml, ['Checks', 'Raw_Data', 'Mapping']);

    // Save hidden version
    const hiddenFile = file.create({
        name: workbookFile.name.replace('.xlsx', '_Client.xlsx'),
        fileType: file.Type.EXCEL,
        contents: hiddenXml,
        folder: runtime.getCurrentScript().getParameter({ name: 'custscript_client_folder' })
    });
    const hiddenId = hiddenFile.save();

    // Generate PDF from a rendered template (not the XLSX XML)
    const pdfFile = render.xmlToPdf({ xmlString: buildPdfTemplate(hiddenXml) });
    pdfFile.name = workbookFile.name.replace('.xlsx', '.pdf');
    pdfFile.folder = hiddenFile.folder;
    pdfFile.save();

    return { workbookId: hiddenId, pdfId: pdfFile.id };
};

The gotcha here is password protection. SuiteScript cannot encrypt XLSX natively. If your compliance requires true file-level encryption, budget the external microservice. Otherwise, NetSuite role permissions + expiring download links satisfy most SOC-2 auditors.

Governance & Performance Guardrails

ScenarioStrategy
>5,000 transaction linesDelegate to Map/Reduce; Suitelet returns "Processing, check email in 5 min"
Multiple subsidiariesAdd subsidiary filter to SuiteQL; run per-subsidiary in parallel Map/Reduce stages
Recurring monthly runSchedule via N/task → task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT })
Template carry-forwardParse prior workbook's xl/styles.xml and xl/worksheets/sheetN.xml to preserve formatting

Monitor execution logs via Customization > Scripting > Script Deployments > [your deployment] > View Logs. Filter on the logs to catch creeping unit consumption before it blows up in production.

What to Check Next

  • SuiteQL permissions, the running role needs Transactions > View and Reports > Financial at minimum
  • File Cabinet folder structure, create a dedicated Financial Packages / [Client] / [Year] / [Month] hierarchy; restrict to Accounting role
  • Email template, use N/email with a merge field for the download link token
  • Audit trail, log every generate/finalize action to a custom record (custrecord_fin_rpt_log) with user, timestamp, parameters, file IDs

The first run takes a day to wire up. The second run takes five minutes. By month three, your controller wonders why you ever tolerated NSPB's timeline.

Put these ideas to work.

Suite Utils builds small NetSuite utilities that fix the specific thing breaking your day. Each one runs as a native SuiteScript SuiteApp inside your account. No sales call, no onboarding.

Browse the utilities

Enjoyed this one?

Get NetSuite tips like this in your inbox. No spam. Practical guides only.

Keep reading