Products Technologies Demo Docs Blog Support Company

How to Import, Edit, and Export Excel XLSX Files in JavaScript

Build a browser workflow to import a local Excel workbook, edit cells and formulas, inspect conversion diagnostics, and download an updated XLSX file with TX Sheet Control.

How to Import, Edit, and Export Excel XLSX Files in JavaScript

Let users open an Excel workbook, make changes in a spreadsheet editor, and download the result from your JavaScript application. TX Sheet Control handles the XLSX conversion and editing; the application supplies the file picker, diagnostics, and download action.

Part 1 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); }
}

Load a Local Excel Workbook

The sample includes a three-sheet sales workbook. Users can also select their own .xlsx file with the file input above the editor. Read the selected File as bytes and pass StreamType.SpreadsheetML to editor.load():

export async function loadXlsx(editor,file) {
    if(file.size>10*1024*1024)throw new Error('Choose a workbook smaller than 10 MB.');
    const {StreamType}=TXTextControl.TXSheetControl;
    const result=await editor.load(new Uint8Array(await file.arrayBuffer()),StreamType.SpreadsheetML);
    // Loading replaces the document. Acquire worksheet handles after the load.
    return {sheet:editor.workbook.sheets.at(0),warnings:result.warnings};
}

export function updateBudget(sheet) {
    sheet.cell('D5').setValue(10);
    sheet.cell('F5').setFormula('=D5*E5');
    return sheet.cell('F5').value;
}

loadXlsx() rejects files above the sample's 10 MB limit before reading them. The file extension helps the picker filter choices; the XLSX parser validates the actual content. A failed or canceled load leaves the current document in place.

A successful load replaces the document. Reacquire worksheet, range, and table handles afterward, as the function does when returning the first worksheet. Keeping a handle from the previous document can lead to stale-handle errors.

Edit Values and Formulas

updateBudget() changes the first order from eight units to ten in D5 and sets F5 to =D5*E5. At a unit price of $125, its revenue becomes $1,250. The workbook total in F12 updates from $5,400 to $5,650, and the linked Summary worksheet follows the change.

The sample after changing the first order. Its three worksheets and formulas remain available in the editor.
The sample after changing the first order. Its three worksheets and formulas remain available in the editor.

Use setValue() for a typed value, setText() for literal text, and setFormula() for an explicit formula. Users can make the same changes through the ribbon, formula bar, and worksheet grid.

Display Import and Export Diagnostics

load() returns a warnings collection. The sample displays those messages in Conversion diagnostics with textContent. A successful import can still contain notices about content that is projected, preserved, or has limited editing support.

After editor.save(StreamType.SpreadsheetML), inspect editor.getXlsxWarnings() as well. Keep diagnostics visible when a workbook uses specialized features; an empty warnings list is useful evidence for a particular file, rather than a guarantee for every Excel document.

Download the Modified Workbook

The complete action wiring below connects file selection, editing, warnings, and download. The shared download() helper creates a Blob with the XLSX MIME type, triggers a named download, and releases the temporary object URL:

import {createEditor,StreamType,download,busy,showWarnings,status} from './common.js';
import {loadXlsx,updateBudget} 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,'import-edit-export.xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  status.textContent='Workbook exported successfully. Review conversion diagnostics.';
 };
 const open=async file=>{model=await loadXlsx(editor,file);showWarnings(model.warnings);status.textContent='Workbook loaded. Review conversion diagnostics below.';};
 const input=document.createElement('input'); input.type='file';input.accept='.xlsx';input.setAttribute('aria-label','Select local Excel workbook');
 document.getElementById('actions').append(input);
 input.addEventListener('change',()=>{const file=input.files[0];if(file)busy('Importing workbook…',()=>open(file)).catch(()=>{});});
 const response=await fetch('./sales-input.xlsx');
 if(!response.ok)throw new Error('Sample workbook could not be loaded.');
 await open(new File([await response.arrayBuffer()],'sales-input.xlsx'));
 addAction('update','Update units and formula',async()=>{updateBudget(editor.workbook.sheets.at(0));status.textContent='First order: 10 units × $125 = $1,250. Total revenue: $5,650.';});
 addAction('export','Download edited XLSX',downloadXlsx);
 return {editor,actions,get model(){return model;}};
}
window.sampleReady=start();
window.sampleReady.catch(error=>{status.textContent=error.message;console.error(error);});

Check the Round Trip

Reopen the downloaded XLSX and verify the things your application depends on: worksheet names, formulas and totals, date and currency formats, column widths, tables, charts, and print settings. For this sample, check three worksheets, F5 = 1250, F12 = 5650, and the linked Summary values.

TX Sheet Control retains supported worksheet features and preserves original package content where the conversion supports it. Preserved content does not automatically become editable. Keep TX-specific dashboards and report-template metadata in TXWB when you need their complete editable behavior.

Read more in the TX Sheet Control documentation.

Next: How to Convert Excel to PDF in JavaScript

Frequently Asked Questions

This sample reads the selected file with the browser File API and imports it locally. Its file-selection code does not upload the workbook.

A successful load replaces the document and invalidates handles from the previous workbook.

Review diagnostics, reopen the XLSX, and verify important values, formulas, worksheet structure, formatting, and specialized features.

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 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.


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.

Share this blog post on:

​​​