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

51 lines
1.5 KiB
HTML
Raw 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>
<script src="http://requirejs.org/docs/release/2.3.3/comments/require.js"></script>
<script>
/* Wire up RequireJS */
require.config({
baseUrl: ".",
name: "app",
paths: {
xlsx: "https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min"
}
});
require(["xlsx"], function(XLSX) {
document.getElementById("xport").addEventListener("click", async() => {
/* fetch JSON data and parse */
const url = "https://sheetjs.com/executive.json";
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>