Skip to content

Examples

ABCrimson edited this page Mar 3, 2026 · 8 revisions

Examples

Common patterns and recipes for modern-xlsx.

Quick Start

import { initWasm, Workbook } from 'modern-xlsx';

await initWasm();

const wb = new Workbook();
const ws = wb.addSheet('Hello');
ws.cell('A1').value = 'Hello, World!';
ws.cell('A2').value = 42;

await wb.toFile('hello.xlsx');

Reading and Modifying

import { readFile } from 'modern-xlsx';

const wb = await readFile('input.xlsx');
const ws = wb.getSheet('Sheet1');

if (ws) {
  console.log(ws.cell('A1').value);
  ws.cell('A1').value = 'Updated!';
  await wb.toFile('output.xlsx');
}

Styling Cells

const headerStyle = wb.createStyle()
  .font({ name: 'Arial', size: 14, bold: true, color: 'FFFFFF' })
  .fill({ pattern: 'solid', fgColor: '4472C4' })
  .alignment({ horizontal: 'center', vertical: 'center' })
  .border({ bottom: { style: 'medium', color: '000000' } })
  .build(wb.styles);

const headers = ['Name', 'Age', 'City'];
headers.forEach((h, i) => {
  const cell = ws.cell(`${String.fromCharCode(65 + i)}1`);
  cell.value = h;
  cell.styleIndex = headerStyle;
});

Formulas

ws.cell('A1').value = 100;
ws.cell('A2').value = 200;
ws.cell('A3').value = 300;
ws.cell('A4').formula = 'SUM(A1:A3)';
ws.cell('B1').formula = 'AVERAGE(A1:A3)';

Merged Cells

ws.cell('A1').value = 'Spans three columns';
ws.addMergeCell('A1:C1');

Column Widths and Row Heights

ws.setColumnWidth(1, 30); // Column A
ws.setRowHeight(1, 40);   // Row 1
ws.setRowHidden(5, true); // Hide row 5

Frozen Panes

// Freeze top row
ws.frozenPane = { rows: 1, cols: 0 };

// Freeze first column
ws.frozenPane = { rows: 0, cols: 1 };

// Freeze both
ws.frozenPane = { rows: 1, cols: 1 };

Data Validation

// Dropdown list
ws.addValidation('B2', {
  validationType: 'list',
  formula1: '"Yes,No,Maybe"',
  showDropDown: true,
  prompt: 'Select an option',
  promptTitle: 'Choice',
});

// Number range
ws.addValidation('C2', {
  validationType: 'whole',
  operator: 'between',
  formula1: '1',
  formula2: '100',
  errorTitle: 'Invalid',
  error: 'Enter a number between 1 and 100',
});

Hyperlinks

ws.cell('A1').value = 'Visit Example';
ws.addHyperlink('A1', 'https://example.com', {
  display: 'Visit Example',
  tooltip: 'Opens example.com',
});

Comments

ws.cell('A1').value = 'Hover for comment';
ws.addComment('A1', 'Author Name', 'This is a comment on A1');

Named Ranges

wb.addNamedRange('SalesTotal', 'Data!$A$1:$A$2');
const range = wb.getNamedRange('SalesTotal');

Document Properties

wb.docProperties = {
  title: 'Sales Report Q4',
  creator: 'Finance Team',
  description: 'Quarterly sales data',
  created: '2026-01-01T00:00:00Z',
};

Rich Text

import { RichTextBuilder } from 'modern-xlsx';

const richText = new RichTextBuilder()
  .bold('Important: ')
  .text('Normal text. ')
  .colored('Red text', 'FF0000')
  .styled('Custom', { bold: true, italic: true, fontSize: 14 })
  .build();

Sheet Conversions

import { aoaToSheet, jsonToSheet, sheetToJson, sheetToCsv } from 'modern-xlsx';

// Array of arrays → rows
const rows = aoaToSheet([['Name', 'Age'], ['Alice', 30]]);

// JSON → rows
const rows = jsonToSheet([{ name: 'Alice', age: 30 }]);

// Rows → JSON
const data = sheetToJson(ws);

// Rows → CSV
const csv = sheetToCsv(ws);

Auto Filter

ws.autoFilter = 'A1:B3';

Page Setup

ws.pageSetup = {
  orientation: 'landscape',
  paperSize: 1,
  fitToWidth: 1,
  fitToHeight: 0,
};

Sheet Protection

ws.sheetProtection = {
  sheet: true,
  selectLockedCells: false,
  selectUnlockedCells: false,
};

Date Handling

import { dateToSerial, serialToDate, isDateFormatCode } from 'modern-xlsx';

dateToSerial({ year: 2026, month: 3, day: 1 }); // 46113
serialToDate(46113); // { year: 2026, month: 3, day: 1 }
isDateFormatCode('yyyy-mm-dd'); // true

Cell Reference Utilities

import { columnToLetter, letterToColumn, decodeCellRef, encodeCellRef } from 'modern-xlsx';

columnToLetter(0);   // 'A'
letterToColumn('A');  // 0
decodeCellRef('B3');  // { row: 2, col: 1 }
encodeCellRef(2, 1); // 'B3'

Browser Download

import { writeBlob } from 'modern-xlsx';

const blob = writeBlob(wb);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'output.xlsx';
a.click();
URL.revokeObjectURL(url);

Barcode & QR Generation

import { Workbook, generateBarcode, encodeQR, renderBarcodePNG, initWasm } from 'modern-xlsx';

await initWasm();
const wb = new Workbook();
const ws = wb.addSheet('Barcodes');

// Embed a QR code into the worksheet
ws.cell('A1').value = 'Product QR';
const { drawing, rels, media } = generateBarcode(wb, ws, {
  type: 'qr',
  data: 'https://example.com/product/123',
  anchor: { from: { col: 1, row: 1 }, to: { col: 4, row: 8 } },
});

// Standalone PNG rendering
const matrix = encodeQR('Hello World');
const pngBytes = renderBarcodePNG(matrix, { scale: 4, margin: 2 });

Supported formats: Code 39, Code 128, EAN-13, UPC-A, ITF-14, GS1-128, QR Code, Data Matrix, PDF417.

Table Layout Engine

Generate styled tables without manual cell coordinate math.

Basic Table

import { initWasm, Workbook, drawTable } from 'modern-xlsx';

await initWasm();

const wb = new Workbook();
const ws = wb.addSheet('Sales');

drawTable(wb, ws, {
  headers: ['Product', 'Region', 'Q1', 'Q2', 'Total'],
  rows: [
    ['Widget', 'North', 45000, 52000, 97000],
    ['Widget', 'South', 38000, 41000, 79000],
    ['Gadget', 'North', 62000, 68000, 130000],
    ['Gadget', 'South', 55000, 59000, 114000],
  ],
  headerColor: '2F5496',
  alternateRowColor: 'D6E4F0',
  freezeHeader: true,
  autoFilter: true,
  columns: [
    { align: 'left', width: 14 },
    { align: 'center', width: 12 },
    { align: 'right', numberFormat: '$#,##0', width: 12 },
    { align: 'right', numberFormat: '$#,##0', width: 12 },
    { align: 'right', numberFormat: '$#,##0', width: 14 },
  ],
});

await wb.toFile('sales-report.xlsx');

JSON Data to Table

import { drawTableFromData } from 'modern-xlsx';

const employees = [
  { name: 'Alice', department: 'Engineering', salary: 95000 },
  { name: 'Bob', department: 'Marketing', salary: 72000 },
  { name: 'Carol', department: 'Design', salary: 88000 },
];

drawTableFromData(wb, ws, employees, {
  headerMap: { name: 'Employee', department: 'Dept', salary: 'Salary' },
  autoWidth: true,
  alternateRowColor: 'F5F5F5',
});

Stacked Tables

const q1 = drawTable(wb, ws, {
  headers: ['Q1 Revenue'],
  rows: [['North: $120K'], ['South: $95K']],
  origin: 'A1',
});

const nextRow = q1.lastDataRow + 2;
drawTable(wb, ws, {
  headers: ['Q2 Revenue'],
  rows: [['North: $135K'], ['South: $102K']],
  origin: `A${nextRow + 1}`,
});

See the full Table Layout Engine guide for merge cells, per-cell overrides, side-by-side composition, and more.

Browser & CDN

Script Tag (IIFE)

<script src="https://cdn.jsdelivr.net/npm/modern-xlsx@0.5.0/dist/modern-xlsx.min.js"></script>
<script>
  (async () => {
    await ModernXlsx.initWasm();
    const wb = new ModernXlsx.Workbook();
    const ws = wb.addSheet('Sheet1');
    ws.cell('A1').value = 'Hello from CDN!';
    ws.cell('B1').value = 42;
    const blob = ModernXlsx.writeBlob(wb);
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'output.xlsx';
    a.click();
  })();
</script>

Web Worker

import { createXlsxWorker } from 'modern-xlsx';

const worker = createXlsxWorker({
  workerUrl: '/modern-xlsx.worker.js',
});

// Read a file in the worker
const data = await worker.readBuffer(xlsxBytes);
console.log(data.sheets[0].name);

// Write in the worker
const output = await worker.writeBuffer(data);
worker.terminate();

Framework Integration

Framework-specific examples are available in the examples/ directory:

Framework Files Pattern
React useXlsx.ts, ExcelExport.tsx Hook + Component
Vue 3 useXlsx.ts, ExcelExport.vue Composable + SFC
Svelte 5 xlsx.svelte.ts, ExcelExport.svelte Rune + Component
Angular xlsx.service.ts, excel-export.component.ts Service + Component

Edge Runtimes

Runtime Example Directory
Cloudflare Workers WASM import, JSON→XLSX API examples/cloudflare-worker/
Deno Deploy npm specifier, Deno.serve examples/deno-deploy/
Service Worker Intercept fetch, generate XLSX examples/service-worker/

Clone this wiki locally