Table to Excel using Sheet.js

Babatunde Adelabu
2 min readAug 21, 2020

--

Most developers have problems converting an HTML table to an Excel file. However, there are ways to do this with pure Javascript but the Microsoft change in its Excel encoding package caused the “Microsoft Excel error: the file is corrupt and cannot be opened” issue, which pushed developers to use different libraries to get the job done and one of those effective libraries is SheetJS.

SheetJS is a Javascript library for parsing and writing an Excel file in various spreadsheet formats. I will explain how to use this library to convert an HTML table to an Excel file in 6 steps. You will need the CDN for both SheetJS and FilesaverJs cause you will be using the two, you just need to attach the two CDN that’s all.

<script src=”https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.3/xlsx.full.min.js"></script><script src=”https://cdn.jsdelivr.net/npm/file-saver@2.0.2/dist/FileSaver.min.js"></script>

Then we begin.

Step 1. Get the table you want to convert by id

var table = document.getElementById(“table”);  // table is the id name given to your table.

Step 2. Convert the table to an Excel Workbook spreadsheet

var wb = XLSX.utils.table_to_book(table, {sheet:”Customer Report”});

XLSX.utils.table_to_book requires two arguments, the first is your table and the second is an object of the method options. the sheet option is the name of your workbook, the method converts the table to a Javascript object ready to be converted to an Excel file.

Step 3. Write to a spreadsheet file

var file = XLSX.write(wb, {bookType: "xlsx", type: "binary"});

Step 4. Create a function to convert the spreadsheet file to binary data for download

function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; return buf;
}

Step 5. use our function to convert the spreadsheet file to binary

var binary = s2ab(file);

Step 6. Use Filesaver function saveAs to download our file

return saveAs(new Blob([binary], {
type: "application/octet-stream"
}), “example.xlsx”);

saveAs function requires two arguments, the first is a blob file and the second is the name we want to give our file, we first convert the spreadsheet file to binary cause saveAs require a blob file and to create one required binary data.

with that, our Excel will be returned for download.

Here is the full code if you need it

--

--

Responses (1)