Convert HTML Table to Excel using JavaScript

by Vincy. Last modified on July 3rd, 2023.

Converting an HTML table to an Excel file is a standard requirement for reporting websites. It will be simple and more straightforward if the conversion occurs on the client side.

There are many client-side and server-side plugins to perform the Excel export. For example, PHPSpreadSheet allows writing data into Excel and exporting.

This article will give different options and approaches to achieving the HTML table to Excel conversion with JavaScript.

View demo

This simple example includes a few lines of JavaScript that build the template for Excel export.

It uses the following steps to convert the exported Excel report of tabular data.

  1. Defines HTML template structure with required meta.
  2. Include the table’s inner HTML into the template.
  3. Marks the location by specifying the protocol to download the file via browser.
  4. Redirect via JavaScript to point to the location with the encoded Excel content.

Quick example

A JavaScript handler to set export template and push HTML table data.

function exportToExcel() {
	var location = 'data:application/vnd.ms-excel;base64,';
	var excelTemplate = '<html> ' +
		'<head> ' +
		'<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/> ' +
		'</head> ' +
		'<body> ' +
		document.getElementById("table-conatainer").innerHTML +
		'</body> ' +
		'</html>'
	window.location.href = location + window.btoa(excelTemplate);
}

 

The below HTML table code displays a product listing, which is static. Refer jsPDF AutoTables examples to render a dynamic table by loading row by row.

The button below this table triggers the export to Excel process on the click event. The exportToExcel() function handles the event and proceeds with the client-side export.

<div id="table-conatainer">
	<table class="striped">
		<thead>
			<tr>
				<th>S.No</th>
				<th>Product Name</th>
				<th>Price</th>
				<th>Model</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>1q</td>
				<td>GIZMORE Multimedia Speaker with Remote Control, Black</td>
				<td>2300</td>
				<td>2020</td>
			</tr>
			<tr>
				<td>2</td>
				<td>Black Google Nest Mini</td>
				<td>3400</td>
				<td>2021</td>
			</tr>
		</tbody>
	</table>
</div>

html table excel javascript

Let us see more options for converting HTML table data into an Excel file.

Option 2: Export as CSV to view in Excel

This example is for parsing the HTML table content via JavaScript. It follows the below steps to export an HTML table to Excel as CSV.

  1. Accessing HTML table element object.
  2. Convert the object into an array of row data.
  3. Iterate row data array to prepare comma-separated values of records.
  4. Set the protocol and content type to export the CSV data prepared from the table.

The below JavaScript function implements the above steps to export table data on the client side.

function exportCSVExcel() {
	var tableElement = document.getElementById("table-product-list");
	var sourceData = "data:text/csv;charset=utf-8,";
	var i = 0;
	while (row = tableElement.rows[i]) {
		sourceData += ([
			row.cells[0].innerText,
			row.cells[1].innerText,
			row.cells[2].innerText,
			row.cells[3].innerText
		]).join(",") + "\r\n";
		i++;
	}
	window.location.href = encodeURI(sourceData);
}

Option 3 – Export the HTML table to Excel using a jQuery-based plugin

The jQuery table2excel plugin is a popular solution for acquiring HTML to Excel export.

It has many features with export core functionalities. Those are,

  1. Excludes/includes HTML tags like inputs, links, or images in the source table HTML.
  2. Excludes some table components referencing that particular element’s class or id selectors.
  3. Provides properties to set file name with which the exported data will be downloaded to the browser.

Include the jQuery and table2excel plugin files in the <head> section below.

There are alternative methods to install the table2excel plugin. Its Github page provides documentation of installation and usage methodologies.

<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script
    src="https://cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script>

Then, initiate the plugin class by pointing to the source HTML table element.

The below JavaScript does the initiation. It sets the options array during instantiation to specify a file name, extension and applicable flags.

function exportCSVExcel() {
	$('#table-product-list').table2excel({
		exclude: ".no-export",
		filename: "download.xls",
		fileext: ".xls",
		exclude_links: true,
		exclude_inputs: true
	});
}

This example uses the same HTML table source for the export operation. The difference is that the source table content marks some rows with no-export class.

This class is configured in the above script with exclude property of this plugin class.

Conclusion:

So, we have seen three simple implementations of adding an HTML table to an Excel feature. Though the export feature is vital, we must have a component that provides a seamless outcome.

I hope the above solution can be a good base for creating such components. It is adaptable for sure to dock more features to have an efficient Excel report generation tool.

View demoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page