13 KiB
title | pagination_prev | pagination_next | sidebar_position |
---|---|---|---|
ReactJS | demos/index | demos/grid/index | 1 |
import current from '/version.js'; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import CodeBlock from '@theme/CodeBlock';
ReactJS is a JS library for building user interfaces.
This demo tries to cover common React data flow ideas and strategies. React familiarity is assumed.
Other demos cover general React deployments, including:
- Static Site Generation powered by NextJS
- iOS and Android applications powered by React Native
- Desktop application powered by React Native Windows + macOS
- React Data Grid UI component
- Glide Data Grid UI component
Installation
The "Frameworks" section covers installation with Yarn and other package managers.
The library can be imported directly from JS or JSX code with:
import { read, utils, writeFile } from 'xlsx';
Internal State
The various SheetJS APIs work with various data shapes. The preferred state depends on the application.
Array of Objects
Typically, some users will create a spreadsheet with source data that should be loaded into the site. This sheet will have known columns.
State
The example presidents sheet has one header row with "Name" and "Index" columns. The natural JS representation is an object for each row, using the values in the first rows as keys:
Spreadsheet | State |
---|---|
|
The React useState
hook can configure the state:
import { useState } from 'react';
/* the component state is an array of presidents */
const [pres, setPres] = useState([]);
import { useState } from 'react';
interface President {
Name: string;
Index: number;
}
/* the component state is an array of presidents */
const [pres, setPres] = useState<President[]>([]);
:::note
The types are informative. They do not enforce that worksheets include the named columns. A runtime data validation library should be used to verify the dataset.
:::
Updating State
The read
and sheet_to_json
functions simplify state updates. They are best used in the function bodies of
useEffect
and useCallback
hooks.
A useEffect
hook can download and update state when a person loads the site:
flowchart LR
url[(Remote\nFile)]
ab[(Data\nArrayBuffer)]
wb(SheetJS\nWorkbook)
ws(SheetJS\nWorksheet)
aoo(array of\nobjects)
state((component\nstate))
url --> |fetch\n\n| ab
ab --> |read\n\n| wb
wb --> |wb.Sheets\nselect sheet| ws
ws --> |sheet_to_json\n\n| aoo
aoo --> |setPres\nfrom `setState`| state
import { useEffect } from 'react';
import { read, utils } from 'xlsx';
/* Fetch and update the state once */
useEffect(() => { (async() => {
/* Download file */
const f = await (await fetch("https://sheetjs.com/pres.xlsx")).arrayBuffer();
// highlight-start
const wb = read(f); // parse the array buffer
const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
const data = utils.sheet_to_json(ws); // generate objects
setPres(data); // update state
// highlight-end
})(); }, []);
import { useEffect } from 'react';
import { read, utils } from 'xlsx';
/* Fetch and update the state once */
useEffect(() => { (async() => {
/* Download file */
const f = await (await fetch("https://sheetjs.com/pres.xlsx")).arrayBuffer();
// highlight-start
const wb = read(f); // parse the array buffer
const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
const data: President[] = utils.sheet_to_json<President>(ws); // generate objects
setPres(data); // update state
// highlight-end
})(); }, []);
Rendering Data
Components typically render HTML tables from arrays of objects. The <tr>
table
row elements are typically generated by mapping over the state array, as shown
in the example JSX code:
<table>
{/* The `thead` section includes the table header row */}
<thead><th>Name</th><th>Index</th></thead>
{/* The `tbody` section includes the data rows */}
<tbody>
{/* generate row (TR) for each president */}
// highlight-start
{pres.map(row => (
<tr>
{/* Generate cell (TD) for name / index */}
<td>{row.Name}</td>
<td>{row.Index}</td>
</tr>
))}
// highlight-end
</tbody>
</table>
Exporting Data
The writeFile
and json_to_sheet
functions simplify exporting data. They are best used in the function bodies of
useCallback
hooks attached to button or other elements.
A callback can generate a local file when a user clicks a button:
flowchart LR
state((component\nstate))
ws(SheetJS\nWorksheet)
wb(SheetJS\nWorkbook)
file[(XLSX\nexport)]
state --> |json_to_sheet\n\n| ws
ws --> |book_new\nbook_append_sheet| wb
wb --> |writeFile\n\n| file
import { useCallback } from 'react';
import { utils, writeFile } from 'xlsx';
/* get state data and export to XLSX */
const exportFile = useCallback(() => {
/* generate worksheet from state */
// highlight-next-line
const ws = utils.json_to_sheet(pres);
/* create workbook and append worksheet */
const wb = utils.book_new();
utils.book_append_sheet(wb, ws, "Data");
/* export to XLSX */
writeFile(wb, "SheetJSReactAoO.xlsx");
}, [pres]);
Complete Component
This complete component example fetches a test file and displays the contents in a HTML table. When the export button is clicked, a callback will export a file:
import React, { useCallback, useEffect, useState } from "react";
import { read, utils, writeFileXLSX } from 'xlsx';
export default function SheetJSReactAoO() {
/* the component state is an array of presidents */
const [pres, setPres] = useState([]);
/* Fetch and update the state once */
useEffect(() => { (async() => {
const f = await (await fetch("https://sheetjs.com/pres.xlsx")).arrayBuffer();
// highlight-start
const wb = read(f); // parse the array buffer
const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
const data = utils.sheet_to_json(ws); // generate objects
setPres(data); // update state
// highlight-end
})(); }, []);
/* get state data and export to XLSX */
const exportFile = useCallback(() => {
// highlight-next-line
const ws = utils.json_to_sheet(pres);
const wb = utils.book_new();
utils.book_append_sheet(wb, ws, "Data");
writeFileXLSX(wb, "SheetJSReactAoO.xlsx");
}, [pres]);
return (<table><thead><th>Name</th><th>Index</th></thead><tbody>
{ /* generate row for each president */
// highlight-start
pres.map(pres => (<tr>
<td>{pres.Name}</td>
<td>{pres.Index}</td>
</tr>))
// highlight-end
}
</tbody><tfoot><td colSpan={2}>
<button onClick={exportFile}>Export XLSX</button>
</td></tfoot></table>);
}
How to run the example (click to show)
:::note
This demo was last run on 2023 February 28 using create-react-app@5.0.1
and
react-scripts@5.0.1
.
:::
-
Run
npx create-react-app@5.0.1 --scripts-version=5.0.1 sheetjs-react
. -
Install the SheetJS dependency and start the dev server:
{\ cd sheetjs-react npm i npm i --save https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz npm start
}
-
Open a web browser and access the displayed URL (
http://localhost:3000
) -
Replace
src/App.js
with thesrc/SheetJSReactAoO.js
example.
The page will refresh and show a table with an Export button. Click the button
and the page will attempt to download SheetJSReactAoA.xlsx
.
- Build the site with
npm run build
, then test withnpx http-server build
. Accesshttp://localhost:8080
with a web browser to test the bundled site.
HTML
The main disadvantage of the Array of Objects approach is the specific nature of the columns. For more general use, passing around an Array of Arrays works. However, this does not handle merge cells well!
The sheet_to_html
function generates HTML that is aware of merges and other
worksheet features. React dangerouslySetInnerHTML
attribute allows code to
set the innerHTML
attribute, effectively inserting the code into the page.
In this example, the component attaches a ref
to the DIV
container. During
export, the first TABLE
child element can be parsed with table_to_book
to
generate a workbook object.
import React, { useCallback, useEffect, useRef, useState } from "react";
import { read, utils, writeFileXLSX } from 'xlsx';
export default function SheetJSReactHTML() {
/* the component state is an HTML string */
const [__html, setHtml] = useState("");
/* the ref is used in export */
const tbl = useRef(null);
/* Fetch and update the state once */
useEffect(() => { (async() => {
const f = await (await fetch("https://sheetjs.com/pres.xlsx")).arrayBuffer();
const wb = read(f); // parse the array buffer
const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
// highlight-start
const data = utils.sheet_to_html(ws); // generate HTML
setHtml(data); // update state
// highlight-end
})(); }, []);
/* get live table and export to XLSX */
const exportFile = useCallback(() => {
// highlight-start
const elt = tbl.current.getElementsByTagName("TABLE")[0];
const wb = utils.table_to_book(elt);
// highlight-end
writeFileXLSX(wb, "SheetJSReactHTML.xlsx");
}, [tbl]);
return ( <>
<button onClick={exportFile}>Export XLSX</button>
// highlight-next-line
<div ref={tbl} dangerouslySetInnerHTML={{ __html }} />
</> );
}
How to run the example (click to show)
:::note
This demo was last run on 2023 February 28 using create-react-app@5.0.1
and
react-scripts@5.0.1
.
:::
-
Run
npx create-react-app@5.0.1 --scripts-version=5.0.1 sheetjs-react
. -
Install the SheetJS dependency and start the dev server:
{\ cd sheetjs-react npm i npm i --save https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz npm start
}
-
Open a web browser and access the displayed URL (
http://localhost:3000
) -
Replace
src/App.js
with thesrc/SheetJSReactHTML.js
example.
The page will refresh and show a table with an Export button. Click the button
and the page will attempt to download SheetJSReactHTML.xlsx
.
- Build the site with
npm run build
, then test withnpx http-server build
. Accesshttp://localhost:8080
with a web browser to test the bundled site.
Rows and Columns
Some data grids and UI components split worksheet state in two parts: an array of column attribute objects and an array of row objects. The former is used to generate column headings and for indexing into the row objects.
The safest approach is to use an array of arrays for state and to generate column objects that map to A1-Style column headers.
The React Data Grid demo uses this approach with the following column and row structure:
/* rows are generated with a simple array of arrays */
const rows = utils.sheet_to_json(worksheet, { header: 1 });
/* column objects are generated based on the worksheet range */
const range = utils.decode_range(ws["!ref"]||"A1");
const columns = Array.from({ length: range.e.c + 1 }, (_, i) => ({
/* for an array of arrays, the keys are "0", "1", "2", ... */
key: String(i),
/* column labels: encode_col translates 0 -> "A", 1 -> "B", 2 -> "C", ... */
name: XLSX.utils.encode_col(i)
}));
Legacy Deployments
The Standalone Scripts play nice with legacy deployments that do not use a bundler.
The legacy demo shows a simple React component transpiled in the browser using Babel standalone library.