This commit is contained in:
SheetJS 2022-07-25 16:48:10 -04:00
parent 8abe41283a
commit ae2a3e7177
6 changed files with 112 additions and 13 deletions

@ -154,7 +154,7 @@ const { webkit } = require('playwright'); // import desired browser
PhantomJS is a headless web browser powered by WebKit. Standalone binaries are
available at <https://phantomjs.org/download.html>
:::warning
:::warning
This information is provided for legacy deployments. PhantomJS development has
been suspended and there are known vulnerabilities, so new projects should use

@ -77,7 +77,7 @@ function SheetJSToTFJSCSV() {
model.compile({ optimizer: tf.train.sgd(0.000001), loss: 'meanSquaredError' });
let base = output;
await model.fitDataset(flat, { epochs: 10, callbacks: { onEpochEnd: async (epoch, logs) => {
setOutput(base += "\n" + epoch + ":" + logs.loss);
setOutput(base += "\n" + epoch + ":" + logs.loss);
}}});
model.summary();
});
@ -165,7 +165,7 @@ async function getData() {
:::caution
While it is more efficient to use low-level operations, JS or CSV interchange
is strongly recommended when possible.
is strongly recommended when possible.
:::

@ -77,7 +77,7 @@ npx browserify xlsxworker.js > worker.js
4) Spin up a local web server:
```
npx http-server
npx http-server
```
5) Access the site <http://localhost:8080/> and use the file input element to
@ -343,7 +343,7 @@ Parcel Bundler should play nice with SheetJS out of the box.
:::warning Parcel Bug
Errors of the form `Could not statically evaluate fs call` stem from a
Errors of the form `Could not statically evaluate fs call` stem from a
[parcel bug](https://github.com/parcel-bundler/parcel/pull/523). Upgrade to
Parcel version 1.5.0 or later.
@ -429,4 +429,103 @@ npx -y parcel index.html
4) Access the page listed in the output (typically `http://localhost:1234`) and
click the "Click to Export!" button to generate a file.
</details>
</details>
## Snowpack
Snowpack works with no caveats.
<details><summary><b>Complete Example</b> (click to show)</summary>
1) Install the tarball using a package manager:
<Tabs>
<TabItem value="npm" label="npm">
<pre><code parentName="pre" {...{"className": "language-bash"}}>{`\
$ npm install --save https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz`}
</code></pre>
</TabItem>
<TabItem value="pnpm" label="pnpm">
<pre><code parentName="pre" {...{"className": "language-bash"}}>{`\
$ pnpm install --save https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz`}
</code></pre>
</TabItem>
<TabItem value="yarn" label="Yarn" default>
<pre><code parentName="pre" {...{"className": "language-bash"}}>{`\
$ yarn add --save https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz`}
</code></pre>
</TabItem>
</Tabs>
2) Save the following to `index.js`:
```js title="index.js"
// highlight-next-line
import { set_fs, utils, version, writeFile } from 'xlsx/xlsx.mjs';
document.getElementById("xport").addEventListener("click", async() => {
/* fetch JSON data and parse */
const url = "https://sheetjs.com/executive.json";
const raw_data = await (await fetch(url)).json();
/* filter for the Presidents */
const prez = raw_data.filter(row => row.terms.some(term => term.type === "prez"));
/* flatten objects */
const rows = prez.map(row => ({
name: row.name.first + " " + row.name.last,
birthday: row.bio.birthday
}));
/* generate worksheet and workbook */
const worksheet = utils.json_to_sheet(rows);
const workbook = utils.book_new();
utils.book_append_sheet(workbook, worksheet, "Dates");
/* fix headers */
utils.sheet_add_aoa(worksheet, [["Name", "Birthday"]], { origin: "A1" });
/* calculate column width */
const max_width = rows.reduce((w, r) => Math.max(w, r.name.length), 10);
worksheet["!cols"] = [ { wch: max_width } ];
/* create an XLSX file and try to save to Presidents.xlsx */
writeFile(workbook, "Presidents.xlsx");
});
```
3) Create a small HTML page that loads the script. Save to `index.html`:
```html title="index.html"
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<h1>SheetJS Presidents Demo</h1>
<button id="xport">Click here to export</button>
<script type="module" src="./index.js"></script>
</body>
</html>
```
:::note
Unlike other bundlers, Snowpack requires a full page including `HEAD` element.
:::
4) Build for production:
```bash
npx snowpack build
```
5) Start a local HTTP server, then go to http://localhost:8080/
```bash
npx http-server build/
```
Click on "Click here to export" to generate a file.
</details>

@ -121,7 +121,7 @@ function generate_sql(ws, wsname) {
const types = {}, hdr = [];
// loop across each row object
aoo.forEach(row =>
aoo.forEach(row =>
// Object.entries returns a row of [key, value] pairs. Loop across those
Object.entries(row).forEach(([k,v]) => {
@ -147,7 +147,7 @@ function generate_sql(ws, wsname) {
// The final array consists of the CREATE TABLE query and a series of INSERTs
return [
// generate CREATE TABLE query and return batch
`CREATE TABLE \`${wsname}\` (${hdr.map(h =>
`CREATE TABLE \`${wsname}\` (${hdr.map(h =>
// column name must be wrapped in backticks
`\`${h}\` ${PG[types[h]]}`
).join(", ")});`
@ -164,7 +164,7 @@ function generate_sql(ws, wsname) {
fields.push(`\`${k}\``);
// when the field type is numeric, `true` -> 1 and `false` -> 0
if(types[k] == "n") values.push(typeof v == "boolean" ? (v ? 1 : 0) : v);
// otherwise,
// otherwise,
else values.push(`'${v.toString().replaceAll("'", "''")}'`);
})
if(fields.length) return `INSERT INTO \`${wsname}\` (${fields.join(", ")}) VALUES (${values.join(", ")})`;
@ -371,8 +371,8 @@ const db = openDatabase('sheetql', '1.0', 'SheetJS WebSQL Test', 2097152);
const stmts = generate_sql(ws, wsname);
// NOTE: tx.executeSql and db.transaction use callbacks. This wraps in Promises
for(var i = 0; i < stmts.length; ++i) await new Promise((res, rej) => {
db.transaction(tx =>
tx.executeSql(stmts[i], [],
db.transaction(tx =>
tx.executeSql(stmts[i], [],
(tx, data) => res(data), // if the query is successful, return the data
(tx, err) => rej(err) // if the query fails, reject with the error
));
@ -528,7 +528,6 @@ const wb = XLSX.utils.json_to_sheet(aoo);
```
### MongoDB Structured Collections
:::warning MongoDB Relicense

@ -59,6 +59,7 @@ The demo projects include small runnable examples and short explainers.
- [`parcel`](./bundler#parcel)
- [`requirejs`](https://github.com/SheetJS/SheetJS/tree/master/demos/requirejs/)
- [`rollup`](https://github.com/SheetJS/SheetJS/tree/master/demos/rollup/)
- [`snowpack`](./bundler#snowpack)
- [`systemjs`](https://github.com/SheetJS/SheetJS/tree/master/demos/systemjs/)
- [`typescript`](https://github.com/SheetJS/SheetJS/tree/master/demos/typescript/)
- [`webpack 2.x`](https://github.com/SheetJS/SheetJS/tree/master/demos/webpack/)

@ -465,7 +465,7 @@ export default {
</details>
</TabItem>
</TabItem>
</Tabs>