forked from sheetjs/docs.sheetjs.com
47 lines
1.4 KiB
Svelte
47 lines
1.4 KiB
Svelte
<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://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>
|