Create Excel File In Javascript (Very Simple Examples)

Welcome to a tutorial on how to create an Excel file in Javascript. Yes, you read that right. We are referring to “browser Javascript”, and not the server-side NodeJS. The dark days have passed and it is actually possible to generate Excel files in Javascript:

  • Load the SheetJS library from a CDN, or host it on your own.
  • var data = [["A", "B"], ["C", "D"]];
  • var wb = XLSX.utils.book_new();
  • wb.SheetNames.push("demo");
  • wb.Sheets["demo"] = XLSX.utils.aoa_to_sheet(data);
  • XLSX.writeFile(wb, "demo.xlsx");

That’s all for the quick introduction, read on for detailed examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

CREATE EXCEL FILE IN JAVASCRIPT

All right, let us now get into the examples of generating an Excel file in Javascript.

 

TUTORIAL VIDEO

 

EXAMPLE 1) GENERATE EXCEL FILE & FORCE DOWNLOAD

1A) THE HTML

1-create-excel.html
<!-- (A) LOAD SHEETJS FROM CDN -->
<!-- https://sheetjs.com/ -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
 
<!-- (B) CLICK TO GENERATE DEMO EXCEL -->
<button id="demo">Download Demo Excel</button>

<!-- (C) JAVASCRIPT -->
<script>
document.getElementById("demo").onclick = () => { ... };
</script>

Yep, that is pretty much everything we need to drive this example.

  1. Load SheetJS from CDNJS, this library is required to create the Excel file… Or save and host it on your own. Will leave a link in the extras section below to their full documentation.
  2. A demo button to start generating the Excel file.
  3. Generate the Excel file when the button is clicked.

 

1B) DUMMY DATA

1-create-excel.html
// (C1) DUMMY DATA
var data = [
  ["Joa Doe", "joa@doe.com"],
  ["Job Doe", "job@doe.com"],
  ["Joe Doe", "joe@doe.com"],
  ["Jon Doe", "jon@doe.com"],
  ["Joy Doe", "joy@doe.com"]
];

For the Javascript, we will first start by defining a nested array of dummy data. Don’t think it needs a lot of explanation, this will get “converted” into rows and columns in the Excel file.

 

 

1C) CREATE A NEW EXCEL OBJECT

1-create-excel.html
// (C2) CREATE NEW EXCEL "FILE"
var workbook = XLSX.utils.book_new(),
    worksheet = XLSX.utils.aoa_to_sheet(data);
workbook.SheetNames.push("First");
workbook.Sheets["First"] = worksheet;

This should be pretty self-explanatory for the folks who already know Excel well, but for the sake of those who are new:

  • A “workbook” is simply “the entire Excel file”.
  • A “worksheet” is a table within a workbook.
  • A workbook can contain multiple worksheets.

So what this section is doing:

  • workbook = XLSX.utils.book_new() Creates a new Excel workbook.
  • worksheet = XLSX.utils.aoa_to_sheet(data) Creates a new worksheet, using the dummy data array above.
  • workbook.SheetNames.push("First") and workbook.Sheets["First"] = worksheet Attach the worksheet to the workbook.

 

1D) FORCE DOWNLOAD

1-create-excel.html
// (C3) "FORCE DOWNLOAD" XLSX FILE
XLSX.writeFile(workbook, "demo.xlsx");

Horray, we now have an Excel object. All that’s left is to “force download” the Excel file, and allow the user to save it.

 

 

EXAMPLE 2) GENERATE EXCEL FILE & UPLOAD TO SERVER

2A) UPLOAD GENERATED EXCEL FILE

2a-upload-excel.html
// (C3) TO BLOB
var xlsblob = new Blob(
  [new Uint8Array(XLSX.write(workbook, { bookType: "xlsx", type: "array" }))],
  {type:"application/octet-stream"}
);
 
// (C4) FORM DATA
var data = new FormData();
data.append("xls", xlsblob, "demo.xlsx");
 
// (C5) UPLOAD TO SERVER
fetch("2b-upload.php", { method: "POST", body: data })
.then(res => res.text())
.then(txt => console.log(txt));

This is an alternative if you want to upload the generated Excel file to the server instead.

  • (C3) Instead of “forcing a download”, we turn the workbook into a blob (binary object).
  • (C4) Attach the Excel blob as form data.
  • (C5) Send the Excel blob to the server… Otherwise also known as “file upload”.

 

2B) SAVE THE UPLOADED EXCEL FILE

2b-upload.php
<?php
echo move_uploaded_file(
  $_FILES["xls"]["tmp_name"],
  __DIR__ . DIRECTORY_SEPARATOR . $_FILES["xls"]["name"]
) ? "OK" : "ERROR" ;

On the server side, we simply save the uploaded Excel file like a “normal file upload”. This is a simple “save uploaded file” snippet in PHP.

 

 

EXTRAS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

EFFICIENCY & PERFORMANCE

Just a quick note that we are holding an entire Excel file in the memory with this example… This will work great for small to medium Excel files, but the massive ones are going to run into performance issues and memory limits. You may want to implement some sort of restrictions on the maximum amount of data, or look at server-side alternatives with streaming.

 

COMPATIBILITY CHECKS

This example will work on all modern “Grade A” browsers.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

7 thoughts on “Create Excel File In Javascript (Very Simple Examples)”

    1. Thanks for sharing. The lack of an API reference is not helping… Shall update this guide in the future, but the blob is still good for storing files in a storage cache or uploading to the server.

Leave a Comment

Your email address will not be published. Required fields are marked *