1. Spreadsheet docs
  2. Developers

Loading and saving files

Open xlsx and CSV files from a URL, a file input or drag and drop; save xlsx to a download, a file handle or your backend; export PDF, HTML and JSON.

A mounted workbook opens .xlsx, .xlsm, .xltx, .csv, .tsv and .txt files, and saves .xlsx, PDF, JSON and its own .8sh document format. Reading and writing run in a Web Worker as streams, so a large file never blocks the page and is never held in memory in one piece.

CallDirectionFormatNeeds a page
wb.openFile(file, { name })inxlsx, xlsm, xltx, csv, tsv, txt, from a File or a BlobYes
wb.saveXlsx(sink)outxlsxNo
sheet.print.toPdf(sink, options)outPDF of one sheetNo, but charts, shapes and pictures are drawn only by a mounted workbook
exportPdf(wb, sheets, sink, options)outPDF of several sheetsAs above
wb.saveDocument(target) / wb.openDocument(blob)out / in.8sh, which keeps everythingNo
wb.toJSON() / wb.fromJSON(data)out / inplain data, following a published schemaNo
wb.rangeToHtml('A1:F20')outan HTML table, for email or a pageNo

Open a file from a URL

openFile(file, { name }) takes a File or a Blob. A nameless Blob is recognised as .xlsx or CSV from its contents; pass name to give the workbook its file name (which also tells the type by its extension):

JavaScript

import { mountWorkbook } from '@8sheets/core';

const wb = await mountWorkbook(document.querySelector('#sheet'), { chrome: 'light' });

async function openFromUrl(url, name) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`${url}: ${response.status}`);
  await wb.openFile(await response.blob(), { name });   // rejects if the file can't be opened
}

await openFromUrl('/templates/invoice.xlsx', 'invoice.xlsx');
wb.activeSheet.range('B4').values = 'ACME Ltd.';

React

import { useRef } from 'react';
import { Sheet } from '@8sheets/react';

export function Invoice({ templateUrl }) {
  const sheet = useRef(null);

  async function load(wb) {
    const blob = await (await fetch(templateUrl)).blob();
    await sheet.current.openFile(blob, { name: 'invoice.xlsx' });
    wb.activeSheet.range('B4').values = 'ACME Ltd.';
  }

  return (
    <div style={{ height: 600 }}>
      <Sheet ref={sheet} options={{ chrome: 'light' }} onReady={load} />
    </div>
  );
}

Vue

<script setup>
import { Sheet } from '@8sheets/vue';

const props = defineProps({ templateUrl: String });

async function load(wb) {
  const blob = await (await fetch(props.templateUrl)).blob();
  await wb.openFile(blob, { name: 'invoice.xlsx' });
  wb.activeSheet.range('B4').values = 'ACME Ltd.';
}
</script>

<template>
  <Sheet :options="{ chrome: 'light' }" style="height: 600px" @ready="load" />
</template>

Angular

import { Component, Input, ViewChild } from '@angular/core';
import { SheetComponent, SheetsWorkbook } from '@8sheets/angular';

@Component({
  selector: 'app-invoice',
  imports: [SheetComponent],
  template: `<eight-sheet class="grid" [options]="{ chrome: 'light' }" (ready)="load($event)" />`,
  styles: `.grid { height: 600px; }`,
})
export class Invoice {
  @Input() templateUrl = '/templates/invoice.xlsx';
  @ViewChild(SheetComponent) sheet!: SheetComponent;

  async load(wb: SheetsWorkbook) {
    const blob = await (await fetch(this.templateUrl)).blob();
    await this.sheet.openFile(blob, { name: 'invoice.xlsx' });
    wb.activeSheet.range('B4').values = 'ACME Ltd.';
  }
}

The file's contents replace the workbook's, and the undo history starts again. The promise rejects when the file can't be opened: a damaged file, a password prompt the user cancelled, or a reader that failed to start. Large files show their first rows while the rest is still loading.

A workbook with a password to open asks the user for it, as the app does. Files from a different origin need CORS headers on that server for fetch to read them.

Open a file the user picks

The built-in File > Open command, the open button in the title bar and dropping a file on the grid already work. To open a file from your own control:

const input = document.querySelector('input[type=file]');   // accept=".xlsx,.xlsm,.xltx,.csv,.tsv,.txt"
input.addEventListener('change', async () => {
  const file = input.files[0];
  if (file) await wb.openFile(file);
});

A File from <input type="file"> or from a drop event has a name and can be passed as it is. showOpenFilePicker() (Chrome and Edge) returns handles: pass await handle.getFile().

Save as xlsx

saveXlsx(sink) writes the workbook through a sink: any object with an async write(bytes) method. Bytes arrive in chunks while the file is written, so a large file never sits in memory twice. It waits for calculation first, so saved values are current.

JavaScript

// A Blob, for a download or an upload.
async function toBlob(wb) {
  const parts = [];
  await wb.saveXlsx({ write: async (bytes) => { parts.push(bytes.slice()); } });
  return new Blob(parts, { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
}

// Download it.
const url = URL.createObjectURL(await toBlob(wb));
Object.assign(document.createElement('a'), { href: url, download: 'report.xlsx' }).click();
URL.revokeObjectURL(url);

// Upload it to your backend.
await fetch('/api/reports/42/file', { method: 'PUT', body: await toBlob(wb) });

// Or write straight into a file the user chose (Chrome and Edge).
const handle = await window.showSaveFilePicker({ suggestedName: 'report.xlsx' });
const writable = await handle.createWritable();
await wb.saveXlsx(writable);
await writable.close();

React

import { useRef } from 'react';
import { Sheet } from '@8sheets/react';

export function Report({ reportId }) {
  const sheet = useRef(null);

  async function save() {
    const parts = [];
    await sheet.current.saveXlsx({ write: async (bytes) => { parts.push(bytes.slice()); } });
    await fetch(`/api/reports/${reportId}/file`, { method: 'PUT', body: new Blob(parts) });
  }

  return (
    <>
      <button onClick={save}>Save to server</button>
      <div style={{ height: 600 }}><Sheet ref={sheet} /></div>
    </>
  );
}

Vue

<script setup>
import { Sheet, useSheet } from '@8sheets/vue';

const props = defineProps({ reportId: String });
const { sheet } = useSheet();

async function save() {
  const parts = [];
  await sheet.value.saveXlsx({ write: async (bytes) => { parts.push(bytes.slice()); } });
  await fetch(`/api/reports/${props.reportId}/file`, { method: 'PUT', body: new Blob(parts) });
}
</script>

<template>
  <button @click="save">Save to server</button>
  <Sheet ref="sheet" style="height: 600px" />
</template>

Angular

import { Component, Input, ViewChild } from '@angular/core';
import { SheetComponent } from '@8sheets/angular';

@Component({
  selector: 'app-report',
  imports: [SheetComponent],
  template: `
    <button (click)="save()">Save to server</button>
    <eight-sheet class="grid" />
  `,
  styles: `.grid { height: 600px; }`,
})
export class Report {
  @Input() reportId = '42';
  @ViewChild(SheetComponent) sheet!: SheetComponent;

  async save() {
    const blob = (await this.sheet.saveXlsx()) as Blob;   // no sink: the component returns a Blob
    await fetch(`/api/reports/${this.reportId}/file`, { method: 'PUT', body: blob });
  }
}

Copy each chunk with bytes.slice() if you keep it, as above: the writer may reuse its buffers. In the core API and the React and Vue components the sink is required; only the Angular component's saveXlsx() returns a Blob when called without one.

What the file keeps. A workbook opened from a file saves everything it came with, including parts 8sheets doesn't use: VBA projects (kept, never run), Power Query definitions, custom XML and unknown parts, each with its relationships. Features with no place in Excel's format are stored in the file's own custom XML parts, which Excel ignores and keeps. See Files and compatibility.

CSV

openFile opens .csv, .tsv and .txt files (told apart by their extension) without asking anything; in the app, a .txt file the user opens goes through the Text Import Wizard first. Values read in the page's region, as typed ones do (see Languages and regions). It replaces the workbook's contents as an .xlsx does, and the user can import with delimiter and column-type choices under Data > Get Data > From Text/CSV. The API has no CSV writer of its own; the app's File > Export Sheet as CSV command is available to users. To build CSV in code, read the values:

const quote = (v) => (v == null ? '' : /[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v));
const used = wb.activeSheet.usedRange;
const csv = (used ? used.values : []).map((row) => row.map(quote).join(',')).join('\r\n');

Values read this way are raw: dates come as serial numbers and numbers without their format.

PDF

sheet.print.toPdf(sink, options) writes one sheet as a PDF, laid out by its page setup (paper, orientation, margins, scaling, print area, print titles, headers and footers). exportPdf(wb, sheets, sink, options) writes several sheets into one file. The PDF is written by 8sheets itself, page by page; charts, shapes, pictures, sparklines and conditional formatting appear as they do on screen.

import { exportPdf } from '@8sheets/core';

const sheet = wb.sheet('Invoice');
sheet.print.set({ orientation: 'portrait', fitToPage: true, fitToWidth: 1, fitToHeight: 1, gridLines: false });

const parts = [];
await sheet.print.toPdf({ write: async (bytes) => { parts.push(bytes.slice()); } }, { title: 'Invoice 2027-014' });
const pdf = new Blob(parts, { type: 'application/pdf' });

// Every sheet in one PDF.
const all = [];
await exportPdf(wb, wb.sheets.map((s) => s.index), { write: async (bytes) => { all.push(bytes.slice()); } });

A before-print listener can cancel a PDF job started through the API. sheet.print.pageInfo() tells which cells land on which page, and sheet.print.watermark sets a picture printed behind the cells. In Angular, call sheet.print.toPdf on the workbook the component gives you; exportPdf is a value import from @8sheets/core, which Angular code doesn't import. For users, File > Print opens a preview with Save as PDF; see Page layout, print and PDF.

JSON

wb.toJSON() returns the whole model as plain data, following the published schema (workbook.schema.json in the package source). wb.fromJSON(data) replaces the contents with it and clears undo, and a new workbook can start from it with the data option.

const data = wb.toJSON();                                      // keep it in your database
const valuesOnly = wb.toJSON({ styles: false, formulas: false });
other.fromJSON(data);                                          // fires workbook-loaded
const copy = await mountWorkbook(element, { data });

JSON leaves out PivotTable definitions, data sheet sources and picture bytes. Pass an array as warnings (wb.toJSON({ warnings })) to learn what was left out of a given workbook.

The .8sh document

wb.saveDocument() saves a .8sh document, which keeps everything, including what Excel can't hold, and wb.openDocument(blob) opens one. With no argument saveDocument returns a Blob; it also takes a file handle or a sink. DOCUMENT_EXTENSION (.8sh) and DOCUMENT_MIME are exported for file pickers and uploads. Use it to store a working copy in your system; use .xlsx for files people take elsewhere.

const doc = await wb.saveDocument();          // a Blob
await fetch('/api/drafts/42', { method: 'PUT', body: doc });
await wb.openDocument(await (await fetch('/api/drafts/42')).blob());

HTML

await wb.rangeToHtml('A1:F20') returns an HTML table of the range with its formatting, for an email body or a page.

Limits

  • openFile needs a mounted workbook, because reading runs in its Worker. In Node a workbook can be created, calculated and saved, but not opened from .xlsx; see Workbooks in Node.
  • The older binary .xls format and OpenDocument .ods are not supported. Workbooks kept in another product's own JSON format must be saved as .xlsx there first.
  • How large a file can be opened depends on the memory of the device and the browser's limits. A workbook of 1,000,000 rows by 20 columns is part of the regular performance tests.