JavaScript Convert Html Table to Excel XLS: Here in this tutorial, we can create an excel file from our HTML table data on the client-side. i.e Export HTML table to Excel (.xlsx) using javascript.
There are many libraries available that create CSV files or xlsx files from the HTML table, but all are giving a prompt message. That is when we open that excel file it prompts a message as The file format and extension of the filename doesn't match. The file could be corrupted or unsafe.
Today in this article will use SheetJS, which allow us to create and open excel file without any prompt message and that's pure in javascript.
The second advantage of using the SheetJs library is that it can easily export large HTML tables into excel, an example is provided below.
You can also check my article on how to convert HTML to image on the client-side.
Steps to export HTML table to excel using JavaScript
- HTML Markup: Add table with some data.
- Import SheetJS Library
- Javascript code: Using SheetJS library export table data into an excel file.
<table id="tbl_exporttable_to_xls" border="1">
<thead>
<th>Sr</th>
<th>Name</th>
<th>Location</th>
<th>Job Profile</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td><p>Amit Sarna</p></td>
<td>Florida</td>
<td>Data Scientist</td>
</tr>
<tr>
<td>2</td>
<td><p>Sagar Gada</p></td>
<td>California</td>
<td>Sr FullStack Dev</td>
</tr>
<tr>
<td>3</td>
<td><p>Ricky Marck</p></td>
<td>Nevada</td>
<td>Sr .Net Dev</td>
</tr>
</tbody>
</table>
<button onclick="ExportToExcel('xlsx')">Export table to excel</button>
Import library code as written below
<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>
<script
function ExportToExcel(type, fn, dl) {
var elt = document.getElementById('tbl_exporttable_to_xls');
var wb = XLSX.utils.table_to_book(elt, { sheet: "sheet1" });
return dl ?
XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }):
XLSX.writeFile(wb, fn || ('MySheetName.' + (type || 'xlsx')));
}
</script>
0 Comments