docs.sheetjs.com/docz/static/requirejs/requirejs.html

51 lines
1.5 KiB
HTML
Raw Permalink Normal View History

2022-07-28 05:36:09 +00:00
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<h1>SheetJS Presidents Demo</h1>
<button id="xport">Click here to export</button>
2023-10-19 05:23:55 +00:00
<script src="http://requirejs.org/docs/release/2.3.6/comments/require.js"></script>
2022-07-28 05:36:09 +00:00
<script>
/* Wire up RequireJS */
require.config({
baseUrl: ".",
name: "app",
paths: {
xlsx: "https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min"
}
});
2023-10-19 05:23:55 +00:00
require(["xlsx"], function(_XLSX) {
2022-07-28 05:36:09 +00:00
document.getElementById("xport").addEventListener("click", async() => {
/* fetch JSON data and parse */
2022-08-21 19:43:30 +00:00
const url = "https://sheetjs.com/data/executive.json";
2022-07-28 05:36:09 +00:00
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 = XLSX.utils.json_to_sheet(rows);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "Dates");
/* fix headers */
XLSX.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 */
XLSX.writeFileXLSX(workbook, "Presidents.xlsx");
});
});
</script>
</body>
</html>