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);
|
2024-06-03 03:25:20 +00:00
|
|
|
|
|
|
|
|
|
/* export to XLSX encoded in a Base64 string */
|
2023-04-01 20:13:16 +00:00
|
|
|
|
const data = writeXLSX(wb, { type: "base64" });
|
2024-06-03 03:25:20 +00:00
|
|
|
|
|
|
|
|
|
/* `writeFile` cannot overwrite, so try to delete file first */
|
|
|
|
|
try {
|
|
|
|
|
await Filesystem.deleteFile({
|
|
|
|
|
path: "SheetJSCap.xlsx",
|
|
|
|
|
directory: Directory.Documents
|
|
|
|
|
});
|
|
|
|
|
} catch(e) { /* ignore error */ }
|
|
|
|
|
|
|
|
|
|
/* attempt to write to the device */
|
2023-04-01 20:13:16 +00:00
|
|
|
|
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>
|