Products Technologies Demo Docs Blog Support Company

How to Load REST API Data into a JavaScript Spreadsheet

Fetch REST API JSON into a JavaScript spreadsheet with TX Sheet Control. Validate and map records, show loading and error states, refresh data, and update dependent formulas.

How to Load REST API Data into a JavaScript Spreadsheet

Connect a JavaScript spreadsheet to application data from a REST endpoint. The sample fetches sales records, validates their fields, maps them into a formatted worksheet, and recalculates revenue and margin after refresh.

Part 8 of the JavaScript Spreadsheet Essentials series.

Run the JavaScript Sample

This example uses TX Sheet Control 2.0.0 with plain JavaScript. Download the complete sample and output files (ZIP). Extract it and open its sample folder.

Copy the complete browser folder from your TX Sheet Control download into sample/public/sheet, retaining its fonts, languages, and notices. Put your signed tx-sheet-control.license beside server.mjs. Use Node.js 22 or later to run the included local host:

npm start

Open http://127.0.0.1:5085. The host serves the files; workbook editing and conversion run in the browser. The HTML supplies the editor host and loads /sheet/tx-sheet-control.min.js followed by app.js.

The shared common.js module creates the editor, awaits its fonts and initial readiness, manages progress messages, and delivers byte downloads:

export const { Spreadsheet, StreamType } = TXTextControl.TXSheetControl;
export const status = document.getElementById('status');

export async function createEditor() {
    const response = await fetch('/license', {cache:'no-store'});
    if (!response.ok) throw new Error('Configure tx-sheet-control.license before starting the sample.');
    const editor = new Spreadsheet(document.getElementById('sheet'), {
        license: (await response.text()).trim(),
        fontCatalogURL: '/sheet/fonts/catalog.json',
        fontBaseURL: '/sheet/fonts/', locale:'en-US', currency:'USD'
    });
    await editor.ready;
    return editor;
}

export function download(bytes, name, mime) {
    const url = URL.createObjectURL(new Blob([bytes], {type:mime}));
    const link = document.createElement('a');
    link.href=url; link.download=name;
    document.body.append(link); link.click(); link.remove();
    setTimeout(()=>URL.revokeObjectURL(url),5000);
}

export function showWarnings(warnings) {
    const list=document.getElementById('diagnostics');
    list.replaceChildren();
    const messages=warnings.length ? warnings.map(w=>typeof w==='string' ? w : w.message ?? JSON.stringify(w))
        : ['No conversion warnings.'];
    for(const message of messages) {
        const item=document.createElement('li'); item.textContent=message; list.append(item);
    }
}

export async function busy(message, action) {
    const buttons=[...document.querySelectorAll('button,input[type=file]')];
    buttons.forEach(button=>button.disabled=true);
    status.textContent=message;
    try { return await action(); }
    catch(error) { status.textContent=error.message; throw error; }
    finally { buttons.forEach(button=>button.disabled=false); }
}

Expose a Sales Endpoint

The sample host serves GET /api/sales as a JSON array. Each record contains an ISO date, region, product, units, unit price, and cost. The included fixture keeps the example repeatable; replace that endpoint with your application's data service.

Keep API credentials on the server when your data source requires a secret. The browser sample calls a same-origin application endpoint, so it does not need a third-party API key in its JavaScript.

Fetch and Validate the Response

refreshSales() checks the HTTP status, parses JSON, and validates the entire response before replacing worksheet data. It also uses an AbortController to stop a request after 15 seconds:

import {validateSales,writeSales} from './sales.js';

export async function refreshSales(editor,url='/api/sales') {
    const controller=new AbortController();
    const timeout=setTimeout(()=>controller.abort(),15000);
    try {
        const response=await fetch(url,{signal:controller.signal,headers:{Accept:'application/json'},cache:'no-store'});
        if(!response.ok)throw new Error(`The sales request failed (${response.status}).`);
        const records=validateSales(await response.json());
        // Validate the entire response before replacing the last successful report.
        const sheet=editor.workbook.sheets.at(0);
        sheet.rename('Sales');
        const result=writeSales(sheet,records);
        await editor.workbook.calculation.recalculateAsync();
        return {sheet,...result};
    } finally {clearTimeout(timeout);}
}

fetch() can resolve for an HTTP error, so the explicit response.ok check is necessary. A malformed record, missing field, nonnumeric amount, or invalid date fails validation. The last successful report remains available for these fetch and validation failures.

Map Application Fields to Cells

The shared helper defines the column order and converts dates to numeric spreadsheet serials. It writes one row per record and adds revenue and margin formulas:

export const sales = [
    { date:'2026-11-02', region:'Europe', product:'Software', units:8, unitPrice:125, cost:700 },
    { date:'2026-11-04', region:'Europe', product:'Services', units:4, unitPrice:175, cost:420 },
    { date:'2026-11-07', region:'Americas', product:'Software', units:12, unitPrice:125, cost:900 },
    { date:'2026-11-10', region:'Americas', product:'Services', units:6, unitPrice:175, cost:650 },
    { date:'2026-11-14', region:'Asia Pacific', product:'Software', units:5, unitPrice:125, cost:500 },
    { date:'2026-11-18', region:'Asia Pacific', product:'Services', units:3, unitPrice:175, cost:300 }
];

export function toExcelDate(isoDate, dateSystem = '1900') {
    if (typeof isoDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(isoDate))
        throw new Error('Use an ISO date in YYYY-MM-DD format.');
    const utc = Date.parse(isoDate + 'T00:00:00Z');
    if (!Number.isFinite(utc) || new Date(utc).toISOString().slice(0,10) !== isoDate)
        throw new Error('Invalid calendar date.');
    // The sample uses modern dates, after Excel's historical 1900 leap-day boundary.
    const epoch = dateSystem === '1904' ? Date.UTC(1904,0,1) : Date.UTC(1899,11,30);
    return (utc - epoch) / 86400000;
}

export function validateSales(records) {
    if (!Array.isArray(records) || records.length === 0 || records.length > 1000)
        throw new Error('Expected between 1 and 1000 sales records.');
    return records.map(record => {
        if (!record || typeof record.region !== 'string' || !record.region.trim() ||
            typeof record.product !== 'string' || !record.product.trim())
            throw new Error('Each record needs a region and product.');
        for (const field of ['units','unitPrice','cost']) {
            if (typeof record[field] !== 'number' || !Number.isFinite(record[field]) || record[field] < 0)
                throw new Error('Sales amounts must be finite nonnegative numbers.');
        }
        toExcelDate(record.date);
        return {...record};
    });
}

export function writeSales(sheet, records) {
    const rows = validateSales(records);
    const lastRow = rows.length + 4;
    const totalRow = lastRow + 2;
    sheet.range('A1:H1006').clear();
    sheet.cell('A1').setText('NORTHSTAR / SALES REPORT');
    sheet.range('A1:H1').merge();
    sheet.cell('A2').setText('November 2026 · Revenue, costs and margin · USD');
    sheet.range('A4:H4').setValues([['Date','Region','Product','Units','Unit price','Revenue','Cost','Margin']]);
    sheet.range(`A5:H${lastRow}`).setValues(rows.map(record => [
        toExcelDate(record.date, sheet.workbook.dateSystem), record.region, record.product,
        record.units, record.unitPrice, null, record.cost, null
    ]));
    rows.forEach((_,index) => {
        const row = index + 5;
        sheet.cell(`F${row}`).setFormula(`=D${row}*E${row}`);
        sheet.cell(`H${row}`).setFormula(`=F${row}-G${row}`);
    });
    sheet.cell(`A${totalRow}`).setText('TOTAL');
    for (const column of ['D','F','G','H'])
        sheet.cell(`${column}${totalRow}`).setFormula(`=SUM(${column}5:${column}${lastRow})`);
    sheet.range('A1:H1').format({fontSize:18,bold:true,textColor:'#762060'});
    sheet.range('A4:H4').format({bold:true,fillColor:'#762060',textColor:'#ffffff'});
    sheet.range(`E5:H${totalRow}`).format({numberFormatCode:'$#,##0.00'});
    sheet.range(`A5:A${lastRow}`).format({numberFormatCode:'yyyy-mm-dd'});
    sheet.range(`A${totalRow}:H${totalRow}`).format({bold:true,fillColor:'#f6e8f3'});
    [112,140,130,70,115,120,110,110].forEach((pixels,index)=>sheet.columns.at(index).setWidth({pixels}));
    sheet.rows.at(0).setHeight({pixels:34});
    sheet.rows.at(3).setHeight({pixels:28});
    return {lastRow,totalRow,count:rows.length};
}

The sample accepts 1-1,000 records. Numeric fields must be finite nonnegative numbers. The mapping writes literal text and numbers; formulas are supplied by the application rather than interpreted from text fields in the API response.

The browser sample after loading six records from its application REST endpoint.
The browser sample after loading six records from its application REST endpoint.

Show Loading and Error States

The Refresh API data button runs the request through the shared busy() helper. It disables sample action buttons during the request, shows a loading message, reports an error if the operation fails, and restores the controls in finally.

import {createEditor,StreamType,download,busy,showWarnings,status} from './common.js';
import {refreshSales} from './model.js';

async function start(){
 const editor=await createEditor();
 const actions={};let model={};
 const addAction=(id,label,action)=>{
  actions[id]=action;const button=document.createElement('button');button.id=id;button.textContent=label;
  button.addEventListener('click',()=>busy('Working…',action).catch(()=>{}));
  document.getElementById('actions').append(button);
 };
 const downloadXlsx=async()=>{
  const bytes=await editor.save(StreamType.SpreadsheetML);
  showWarnings(editor.getXlsxWarnings());
  download(bytes,'rest-api.xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  status.textContent='Workbook exported successfully. Review conversion diagnostics.';
 };
 const refresh=async()=>{model=await refreshSales(editor);status.textContent=model.count+' records loaded from /api/sales · Revenue: '+model.sheet.cell('F'+model.totalRow).displayText;};
 addAction('refresh','Refresh API data',async()=>{await refresh();});
 addAction('export','Download current XLSX',downloadXlsx);
 await busy('Loading sales from the API…',refresh);
 return {editor,actions,get model(){return model;}};
}
window.sampleReady=start();
window.sampleReady.catch(error=>{status.textContent=error.message;console.error(error);});

The status element uses role="status" so progress and results are available to assistive technology. Only display a success count after the response has been mapped successfully.

Refresh Dependent Calculations

Once rows are written, workbook.calculation.recalculateAsync() settles dependent calculations. The initial six records produce $5,400 in revenue and $1,930 in margin. Changing the first order to ten units in the API response produces $5,650 in revenue.

The browser checks exercise successful loading, a changed response, an HTTP failure, and an invalid numeric field. Both failure cases retain the previous $5,400 report. A successful refresh replaces the mapped report area; if users also edit those cells, define whether refresh should overwrite their changes or require an explicit choice.

Download a Snapshot

The Download current XLSX action exports the current worksheet through StreamType.SpreadsheetML. The downloaded file is a snapshot of the loaded data and formulas; opening it later does not automatically call your REST endpoint.

For cross-origin services, configure the service's CORS and authentication policies for the actual deployment. Keep the spreadsheet mapping independent of transport details so the same report can also use cached records or a different application endpoint.

Read more in the TX Sheet Control documentation.

Previous: How to Create an Excel XLSX File in JavaScript

Frequently Asked Questions

No. Check response.ok before reading and applying the response.

The sample validates it before writing cells, so fetch and validation failures leave the last successful report in place.

No. It contains the current data and formulas as a workbook snapshot. Refreshing API data is an action in the web application.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

TX Sheet Control

Excel-compatible spreadsheet editing, a robust calculation engine, and interactive dashboards for business applications.

Learn more about TX Sheet Control

Related Posts

JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create an Excel XLSX File in JavaScript

Create an Excel XLSX file from scratch in JavaScript. Add worksheets, write typed data and formulas, format headers and currency, set column widths, and download the workbook.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create an ODS File in JavaScript

Create an ODS workbook in JavaScript with text, numbers, formulas, and currency formatting. Download it, reopen it in TX Sheet Control, and check its standard spreadsheet content in LibreOffice Calc.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Apply Conditional Formatting in a JavaScript Spreadsheet

Apply conditional formatting in a JavaScript spreadsheet: highlight overdue invoices and negative margins, add revenue data bars and target color scales, and update the rules through cell edits.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Create Pivot Tables in JavaScript

Create a JavaScript PivotTable from sales records with TX Sheet Control. Configure row and column fields, sum revenue, filter regions, refresh source edits, and export a native Excel PivotTable.


JavaScriptExcelJavaScript Spreadsheet Essentials

How to Export JSON Data to Excel in JavaScript

Export JSON records to a formatted Excel workbook in JavaScript. Map fields, retain numeric values, format dates and currency, calculate totals, and download XLSX.

Share this blog post on:

​​​