74 lines
2.4 KiB
Markdown
74 lines
2.4 KiB
Markdown
|
---
|
||
|
title: Local Storage API
|
||
|
pagination_prev: demos/grid
|
||
|
pagination_next: demos/worker
|
||
|
sidebar_custom_props:
|
||
|
type: web
|
||
|
---
|
||
|
|
||
|
The Storage API, encompassing `localStorage` and `sessionStorage`, describes
|
||
|
simple key-value stores that only support string values and keys.
|
||
|
|
||
|
Arrays of objects can be stored using `JSON.stringify` using row index as key:
|
||
|
|
||
|
```js
|
||
|
const aoo = XLSX.utils.sheet_to_json(ws);
|
||
|
for(var i = 0; i < aoo.length; ++i) localStorage.setItem(i, JSON.stringify(aoo[i]));
|
||
|
```
|
||
|
|
||
|
Recovering the array of objects is possible by using `JSON.parse`:
|
||
|
|
||
|
```js
|
||
|
const aoo = [];
|
||
|
for(var i = 0; i < localStorage.length; ++i) aoo.push(JSON.parse(localStorage.getItem(i)));
|
||
|
const ws = XLSX.utils.json_to_sheet(aoo);
|
||
|
```
|
||
|
|
||
|
This example will fetch <https://sheetjs.com/data/cd.xls>, fill `localStorage` with
|
||
|
rows, then generate a worksheet from the rows and write to a new file.
|
||
|
|
||
|
:::caution
|
||
|
|
||
|
This example is for illustration purposes. If array of objects is available, it
|
||
|
is strongly recommended to convert that array to a worksheet directly.
|
||
|
|
||
|
:::
|
||
|
|
||
|
```jsx live
|
||
|
function SheetJStorage() {
|
||
|
const [url, setUrl] = React.useState("https://sheetjs.com/data/cd.xls");
|
||
|
const set_url = React.useCallback((evt) => setUrl(evt.target.value));
|
||
|
const [out, setOut] = React.useState("");
|
||
|
const xport = React.useCallback(async() => {
|
||
|
// get first worksheet data as array of objects
|
||
|
const ab = await (await fetch(url)).arrayBuffer();
|
||
|
const wb = XLSX.read(ab), wsname = wb.SheetNames[0];
|
||
|
const aoo = XLSX.utils.sheet_to_json(wb.Sheets[wsname]);
|
||
|
|
||
|
// reset and populate localStorage
|
||
|
localStorage.clear();
|
||
|
for(var i = 0; i < aoo.length; ++i) localStorage.setItem(i, JSON.stringify(aoo[i]));
|
||
|
|
||
|
// create new array of objects from localStorage
|
||
|
const new_aoo = [];
|
||
|
for(var i = 0; i < localStorage.length; ++i) {
|
||
|
const row = JSON.parse(localStorage.getItem(i));
|
||
|
new_aoo.push(row);
|
||
|
}
|
||
|
|
||
|
setOut(`Number of rows in LocalStorage: ${localStorage.length}`);
|
||
|
|
||
|
// create and export workbook
|
||
|
const new_ws = XLSX.utils.json_to_sheet(new_aoo);
|
||
|
const new_wb = XLSX.utils.book_new();
|
||
|
XLSX.utils.book_append_sheet(new_wb, new_ws, "Sheet1");
|
||
|
XLSX.writeFile(new_wb, "SheetJStorage.xlsx");
|
||
|
});
|
||
|
|
||
|
return ( <> {out && (<><a href={url}>{url}</a><pre>{out}</pre></>)}
|
||
|
<b>URL: </b><input type="text" value={url} onChange={set_url} size="50"/>
|
||
|
<br/><button onClick={xport}><b>Fetch!</b></button>
|
||
|
</> );
|
||
|
}
|
||
|
```
|