Hướng dẫn js create excel file
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 using client-side Javascript – Read on for the example! ⓘ I have included a zip file with all the source code at
the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in. Firstly, here is the download link to the example code as promised. If you spot a bug, feel free to comment below. I try to answer
short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming. Click here to download all the example source code, I have released it under
the MIT license, so feel free to build on top of it or use it in your own project. All right, let us now get into the example of generating an Excel file in Javascript and offering it as a download. PART 1) THE HTMLcreate-excel.html
Yep, that is pretty much everything we need to drive the example.
PART 2) THE JAVASCRIPT2A) DUMMY DATAcreate-excel.html
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. 2B) CREATE A NEW EXCEL OBJECTcreate-excel.html
This should be pretty self-explanatory for the folks who already know Excel well, but for the sake of those who are new:
So what this section is doing:
2C) CONVERT TO BLOBcreate-excel.html
Horray, we now have an Excel object, all that’s left is to “save it as an Excel file on the hard disk”. That is easier said than done… This part got me stuck for an hour, researching “how to convert a binary string into a Blob object”.
2D) OFFER AS A FILE DOWNLOADcreate-excel.html
Finally, we create a temporary object URL for the Excel blob object, and “force a download”. The end. P.S. The “use Javascript to click on a download link” trick may not work on all browsers due to security restrictions. The safer way is to attach the download link to the page, and let the user manually click on it. COMPATIBILITY CHECKS
This example will work on all modern “Grade A” browsers. EFFICIENCY & PERFORMANCEJust 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. LINKS & REFERENCES
THE ENDThank 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! |