Home › Blog

JSON to Excel in JavaScript with SheetJS

Four SheetJS calls turn an array of objects into an Excel download. This guide covers those calls, then the details that bite in real data: column order, widths, dates and nested values.

The four calls

npm i https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz
import * as XLSX from 'xlsx';

const rows = [
  { id: 1, name: 'Ada', city: 'London' },
  { id: 2, name: 'Grace', city: 'New York' },
];

const sheet = XLSX.utils.json_to_sheet(rows);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, sheet, 'People');
XLSX.writeFile(workbook, 'people.xlsx');

In the browser, writeFile starts a download. In Node.js with the ES module build, call XLSX.set_fs(fs) first, or it throws cannot save file. The keys of the objects become the header row, in the order they first appear.

Column order

Pass header to put some columns first. Keys you leave out still appear, after the ones you listed:

XLSX.utils.json_to_sheet(rows, { header: ['name', 'id'] });
// header row: name | id | city

Column widths and sheet names

Widths go in the sheet's !cols array, measured in characters with wch:

sheet['!cols'] = [{ wch: 12 }, { wch: 6 }, { wch: 14 }];

Sheet names follow Excel's rules. A name longer than 31 characters makes book_append_sheet throw Sheet name cannot exceed 31 chars, so trim names you build from user input.

Dates

A JavaScript Date in your data becomes a real date cell. A date string such as "2026-01-15" stays text. Convert strings to Date objects first if people will sort or filter by date in Excel.

Nested objects and arrays

json_to_sheet has no cell value for an object or an array, and leaves those cells empty. Flatten the records first. This is the function the JSON to Excel converter and the vue3-json-to-excel component use:

function flatten(value, prefix, out) {
  Object.keys(value).forEach((key) => {
    const path = prefix ? prefix + '.' + key : key;
    const item = value[key];
    if (Array.isArray(item)) out[path] = JSON.stringify(item);
    else if (item !== null && typeof item === 'object') flatten(item, path, out);
    else out[path] = item;
  });
  return out;
}

const sheet = XLSX.utils.json_to_sheet(rows.map((row) => flatten(row, '', {})));

Nested objects become dotted columns like shipping.city and arrays become JSON text in one cell. Nested JSON to Excel covers the other layouts.

In a Vue 3 app

If your app is built with Vue 3, the vue3-json-to-excel component wraps these calls in a download link. See Vue 3 export to Excel.