vite-sheet

This commit is contained in:
SheetJS 2023-06-06 23:48:13 -04:00
parent 709553e22e
commit 063aec617b
3 changed files with 57 additions and 22 deletions
docz

@ -1,14 +1,32 @@
--- ---
title: ViteJS title: ViteJS
sidebar_class_name: red
sidebar_label: ViteJS
description: Make static websites from spreadsheets using ViteJS. Seamlessly integrate data into your website using SheetJS. Empower non-technical people to write content from Excel.
pagination_prev: demos/net/index pagination_prev: demos/net/index
pagination_next: demos/mobile/index pagination_next: demos/mobile/index
sidebar_custom_props: sidebar_custom_props:
type: bundler type: bundler
--- ---
# ViteJS Spreadsheet Plugins
import current from '/version.js'; import current from '/version.js';
import CodeBlock from '@theme/CodeBlock'; import CodeBlock from '@theme/CodeBlock';
[ViteJS](https://vitejs.dev/) is a modern build tool for generating static sites.
It has a robust JavaScript-powered plugin system[^1]
[SheetJS](https://sheetjs.com) is a JavaScript library for reading and writing
data from spreadsheets.
This demo uses ViteJS and SheetJS to pull data from a spreadsheet and display
the content in an HTML table. We'll explore how to load SheetJS in a ViteJS
plugin and compare a few different data loading strategies.
The ["Complete Demo"](#complete-demo) section includes a complete website powered
by an XLSX spreadsheet.
:::note :::note
This demo covers static asset imports. For processing files in the browser, the This demo covers static asset imports. For processing files in the browser, the
@ -16,25 +34,21 @@ This demo covers static asset imports. For processing files in the browser, the
::: :::
## Loaders ## Plugins
ViteJS supports static asset imports, but the default raw loader interprets data ViteJS supports static asset imports[^2], but the default raw loader interprets data
as UTF-8 strings. This corrupts binary formats like XLSX and XLS, but a custom as UTF-8 strings. This corrupts binary formats like XLSX and XLS, but a custom
loader can override the default behavior. loader can override the default behavior.
:::note Recommendation For simple tables of data, ["Pure Data Plugin"](#pure-data-plugin) is strongly
For simple tables of data, ["Pure Data Loader"](#pure-data-loader) is strongly
recommended. The heavy work is performed at build time and the generated site recommended. The heavy work is performed at build time and the generated site
only includes the raw data. only includes the raw data.
For more complex parsing or display logic, ["Base64 Loader"](#base64-loader) is For more complex parsing or display logic, ["Base64 Plugin"](#base64-plugin) is
preferable. Since the raw parsing logic is performed in the page, the library preferable. Since the raw parsing logic is performed in the page, the library
will be included in the final bundle. will be included in the final bundle.
::: ### Pure Data Plugin
### Pure Data Loader
For a pure static site, a plugin can load data into an array of row objects. The For a pure static site, a plugin can load data into an array of row objects. The
SheetJS work is performed in the plugin. The library is not loaded in the page! SheetJS work is performed in the plugin. The library is not loaded in the page!
@ -54,6 +68,8 @@ flowchart LR
aoo --> |main.js\nfrontend code| html aoo --> |main.js\nfrontend code| html
``` ```
This ViteJS plugin will read spreadsheets using the SheetJS `read` method[^3]
and generate arrays of row objects with `sheet_to_json`[^4]:
```js title="vite.config.js" ```js title="vite.config.js"
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
@ -77,19 +93,20 @@ export default defineConfig({
}); });
``` ```
This loader uses the query `sheetjs`: In frontend code, the loader will look for all modules with a `?sheetjs`
query string. The default export is an array of row objects:
```js title="main.js" ```js title="main.js"
import data from './data.xlsx?sheetjs'; import data from './data.xlsx?sheetjs';
document.querySelector('#app').innerHTML = `<div><pre> document.querySelector('#app').innerHTML = `<div><pre>
${data.map(row => JSON.stringify(row)).join("\n")} ${data.map(row => JSON.stringify(row)).join("\n")}
</pre></div>`; </pre></div>`;
``` ```
### Base64 Loader ### Base64 Plugin
This loader pulls in data as a Base64 string that can be read with `XLSX.read`. This plugin pulls in data as a Base64 string that can be read with `read`[^5].
While this approach works, it is not recommended since it loads the library in While this approach works, it is not recommended since it loads the library in
the front-end site. the front-end site.
@ -108,6 +125,9 @@ flowchart LR
aoo --> |main.js\nfrontend code| html aoo --> |main.js\nfrontend code| html
``` ```
This ViteJS plugin will read spreadsheet files and export the data as a Base64
string. SheetJS is not imported in the plugin:
```js title="vite.config.js" ```js title="vite.config.js"
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
@ -130,7 +150,7 @@ export default defineConfig({
``` ```
When importing using the `b64` query, the raw Base64 string will be exposed. When importing using the `b64` query, the raw Base64 string will be exposed.
This can be read directly with `XLSX.read` in JS code: `read` will process the Base64 string using the `base64` input type[^6]:
```js title="main.js" ```js title="main.js"
import { read, utils } from "xlsx"; import { read, utils } from "xlsx";
@ -138,7 +158,7 @@ import { read, utils } from "xlsx";
/* reference workbook */ /* reference workbook */
import b64 from './data.xlsx?b64'; import b64 from './data.xlsx?b64';
/* parse workbook and export first sheet to CSV */ /* parse workbook and export first sheet to CSV */
const wb = read(b64); const wb = read(b64, { type: "base64" });
const wsname = wb.SheetNames[0]; const wsname = wb.SheetNames[0];
const csv = utils.sheet_to_csv(wb.Sheets[wsname]); const csv = utils.sheet_to_csv(wb.Sheets[wsname]);
@ -152,10 +172,13 @@ ${csv}
:::note :::note
This demo was tested on 2023 May 24 against `vite v4.3.8`. This demo was tested on 2023 June 06 against `vite v4.3.9`.
::: :::
The demo walks through the process of creating a new ViteJS website from scratch.
A Git repository with the completed site can be cloned[^7].
### Initial Setup ### Initial Setup
1) Create a new site with the `vue-ts` template and install the SheetJS package: 1) Create a new site with the `vue-ts` template and install the SheetJS package:
@ -261,6 +284,13 @@ JSON.parse('[{"Name":"Bill Clinton","Index":42}
Searching for `BESSELJ` should reveal no results. The SheetJS scripts are not Searching for `BESSELJ` should reveal no results. The SheetJS scripts are not
included in the final site! included in the final site!
:::note
ViteJS also supports "Server-Side Rendering". In SSR, only the HTML table
would be added to the final page. Details are covered in the ViteJS docs[^8].
:::
### Base64 Test ### Base64 Test
8) Run the dev server: 8) Run the dev server:
@ -316,3 +346,13 @@ Searching for `BESSELJ` should match the code:
``` ```
The SheetJS library is embedded in the final site. The SheetJS library is embedded in the final site.
[^1]: See ["Using Plugins"](https://vitejs.dev/guide/using-plugins.html) in the ViteJS documentation.
[^2]: See ["Static Asset Handling"](https://vitejs.dev/guide/assets.html) in the ViteJS documentation.
[^3]: See [`sheet_to_json` in "Utilities"](/docs/api/utilities/#array-output)
[^4]: See [`read` in "Parsing Options"](/docs/api/parse-options)
[^5]: See [`read` in "Parsing Options"](/docs/api/parse-options)
[^6]: See [the "base64" type in "Parsing Options"](/docs/api/parse-options#input-type)
[^7]: See [`SheetJS/sheetjs-vite`](https://git.sheetjs.com/sheetjs/sheetjs-vite/) on the SheetJS git server.
[^8]: See ["Server-Side Rendering"](https://vitejs.dev/guide/ssr.html) in the ViteJS documentation.

@ -38,13 +38,8 @@ remove the field is to use a `projection` to suppress the ID:
```js ```js
/* generate an array of objects from a collection */ /* generate an array of objects from a collection */
const aoo = await collection.find({}, {projection:{_id:0}}).toArray(); const aoo = await collection.find({}, {projection:{_id:0}}).toArray();
```
Worksheets can be generated from the result using `json_to_sheet`:
```js
/* generate a worksheet from a collection */ /* generate a worksheet from a collection */
const aoo = await collection.find({}, {projection:{_id:0}}).toArray();
const ws = utils.json_to_sheet(aoo); const ws = utils.json_to_sheet(aoo);
``` ```

@ -83,7 +83,7 @@ const config = {
position: 'right', position: 'right',
}, },
{ {
href: 'https://git.sheetjs.com/sheetjs/sheetjs', href: 'https://git.sheetjs.com/sheetjs/sheetjs/issues',
label: 'Source', label: 'Source',
position: 'right', position: 'right',
}, },