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

47 lines
1.5 KiB
Svelte
Raw Normal View History

2023-04-01 20:13:16 +00:00
<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() => {
2024-04-26 04:16:13 +00:00
const f = await (await fetch("https://docs.sheetjs.com/pres.xlsx")).arrayBuffer();
2023-04-01 20:13:16 +00:00
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>