forked from sheetjs/docs.sheetjs.com
		
	
		
			
				
	
	
		
			51 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
			
		
		
	
	
			51 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
<!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.6/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/data/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>
 |