docs.sheetjs.com/docz/static/cap/App.svelte

47 lines
1.5 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<script>
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { onMount } from 'svelte';
import { read, utils, version, writeXLSX } from 'xlsx';
let html = "";
let tbl;
/* Fetch and update the state once */
onMount(async() => {
const f = await (await fetch("https://docs.sheetjs.com/pres.xlsx")).arrayBuffer();
const wb = read(f); // parse the array buffer
const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
html = utils.sheet_to_html(ws); // generate HTML and update state
});
/* get state data and export to XLSX */
async function exportFile() {
const elt = tbl.getElementsByTagName("TABLE")[0];
const wb = utils.table_to_book(elt);
/* generate Base64 string for Capacitor */
const data = writeXLSX(wb, { type: "base64" });
/* write */
await Filesystem.writeFile({
path: "SheetJSCap.xlsx",
data,
directory: Directory.Documents
});
alert(`Exported to ${Directory.Documents}/SheetJSCap.xlsx`);
}
/* show file picker, read file, load table */
async function importFile(evt) {
const f = evt.target.files[0];
const wb = read(await f.arrayBuffer());
const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
html = utils.sheet_to_html(ws); // generate HTML and update state
}
</script>
<main>
<h3>SheetJS × CapacitorJS { version }</h3>
<input type="file" on:change={importFile}/>
<button on:click={exportFile}>Export XLSX</button>
<div bind:this={tbl}>{@html html}</div>
</main>