docs.sheetjs.com/docz/docs/03-demos/02-grid/01-xs.md
2023-07-21 05:17:32 -04:00

3.3 KiB

title pagination_prev pagination_next
x-spreadsheet demos/frontend/index demos/net/index
<head> </head>

With a familiar UI, x-spreadsheet is an excellent choice for a modern editor.

Click here for a live standalone integration demo.

Live Demo

:::note

Due to CSS conflicts between the data grid and the documentation generator, features like scrolling may not work as expected.

The linked demo uses a simple HTML page.

:::

function SheetJSXSpread() {
  const [url, setUrl] = React.useState("https://sheetjs.com/pres.numbers");
  const [done, setDone] = React.useState(false);
  const ref = React.useRef(); // ref to DIV container
  const set_url = (evt) => setUrl(evt.target.value);

  return ( <>
    <div height={300} width={300} ref={ref}/>
    {!done && ( <>
      <b>URL: </b><input type="text" value={url} onChange={set_url} size="50"/>
      <br/><button onClick={async() => {
        /* fetch and parse workbook */
        const wb = XLSX.read(await (await fetch(url)).arrayBuffer());
        /* set up grid and load data */
        x_spreadsheet(ref.current).loadData(stox(wb));
        setDone(true);
      }}><b>Fetch!</b></button>
    </> )}
  </> );
}

Integration Library

The integration library can be downloaded from the SheetJS CDN:

When used in a browser tag, it exposes two functions: xtos and stox.

  • stox(worksheet) returns a data structure suitable for grid.loadData
  • xtos(data) accepts the result of grid.getData and generates a workbook

Reading Data

The following snippet fetches a spreadsheet and loads the grid:

(async() => {
  const ab = await (await fetch("https://sheetjs.com/pres.numbers")).arrayBuffer();
  grid.loadData(stox(XLSX.read(ab)));
})();

The same pattern can be used in file input elements and other data sources.

Writing Data

The following snippet exports the grid data to a file:

/* build workbook from the grid data */
XLSX.writeFile(xtos(grid.getData()), "SheetJS.xlsx");

Other Details

Obtaining the Library

The x-data-spreadsheet NodeJS packages include a minified script that can be directly inserted as a script tag. The unpkg CDN also serves this script:

<!-- x-spreadsheet stylesheet -->
<link rel="stylesheet" href="https://unpkg.com/x-data-spreadsheet/dist/xspreadsheet.css"/>
<!-- x-spreadsheet library -->
<script src="https://unpkg.com/x-data-spreadsheet/dist/xspreadsheet.js"></script>

Previewing and Editing Data

The HTML document needs a container element:

<div id="gridctr"></div>

Grid initialization is a one-liner:

var grid = x_spreadsheet(document.getElementById("gridctr"));

x-spreadsheet handles the entire edit cycle. No intervention is necessary.

Additional Features

This demo barely scratches the surface. The underlying grid component includes many additional features that work with SheetJS Pro.