Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

Export Hierarchical (Multi-Level) HTML Table With Styles Using jQuery

4.60/5 (5 votes)
13 Aug 2015CPOL2 min read 20.6K  
Export Hierarchical (Multi-Level) HTML Table With Styles Using jQuery

Introduction

We are all familiar with HTML tables. What if we want to export that HTML table to Excel? What if we want to do it in the client side itself? Yeah, of course using jQuery. Please read here for the basic exporting technique: Export From HTML Table Using jQuery.

Background

In the preceding article, you can determine whether we are exporting a single-level HTML table. What if we need to do that for a multi-level HTML table? The hierarchy must be applied to the Excel file we exported. That too is without using any third-party plug-ins! Sounds cool, right?

Using the Code

So shall we start? I hope you said yes.

What We Need First

Yeah you are right, we need a multi-level HTML table that we will now export. Let us say I have an HTML table as follows:

HTML
<table id="multiLevelTable">
        <caption>My Multi Level Table</caption>
        <thead>
            <tr>
                <th colspan="2" rowspan="2">Column 0</th>
                <th rowspan="2">Column 1</th>
                <th colspan="2">Column 2</th>
            </tr>
            <tr>
                <th>Column 2a</th>
                <th>Column 2b</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th rowspan="2">Row 1</th>
                <th>Row 1a</th>
                <td>123</td>
                <td>456</td>
                <td>789</td>
            </tr>
            <tr>
                <th>Row 1b</th>
                <td>123</td>
                <td>456</td>
                <td>789</td>
            </tr>
            <tr>
                <th colspan="2">Row 2</th>
                <td>123</td>
                <td>456</td>
                <td>789</td>
            </tr>
        </tbody>
    </table>

What next?

Apply Some Styles

Please add the following styles:

CSS
<style>
    td,th,thead,caption,tr{
        text-align:center;border:1px solid #ccc;
    }
        caption {
            background-color:#ccc;
        }

Is that done?

Add the jQuery Reference

JavaScript
<script src="Contents/jquery-1.9.1.js"></script>

Create an Element On Which We Need to Fire the Click Event.

XML
<div onclick="exportThis()" style="cursor: pointer; border: 1px solid #ccc; text-align: center;
width:19%;">Export Multi Level Table to Excel</div>

Please note that we have called the function exportThis in onclick. Shall we go and see what we can write in that function?

exportThis function

The following is the code inside in the function.

JavaScript
var exportThis = (function () {
            var uri = ‘data:application/vnd.ms-excel;base64,’,
template = ‘<html xmlns:o="urn:schemas-microsoft-com:office:office" 
	xmlns:x="urn:schemas-microsoft-com:office:excel"  
	xmlns="http://www.w3.org/TR/REC-html40″><head> 
	<!–[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets> 
	<x:ExcelWorksheet><x:Name>{worksheet}</x:Name> 
	<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions> 
	</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook> 
	</xml><![endif]–></head><body> 
	<table>{table}</table></body></html>’,
                base64 = function (s) {
                    return window.btoa(unescape(encodeURIComponent(s)))
                },
                format = function (s, c) {
                    return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; })
                }
            return function () {
                var ctx = { worksheet: ‘Multi Level Export Table Example’ || 
		‘Worksheet’, table: document.getElementById("multiLevelTable").innerHTML }
                window.location.href = uri + base64(format(template, ctx))
            }
        })()

In the preceding specified function, you can see the following parts:

  • Uri
  • base64
  • format
  • template

So we will discuss those terms now.

If you are confused about the terms URI and URL, please read here: What is the difference between URI, URL and URN?

To be familiar with the base 64 encoding, please read: What is base 64 encoding used for?

The format part is cross-checking the data, whether it has some invalid characters or not. You can see a regex in the function.

The template is the structure of the Excel file; we are using the w3 format.

What It Does

Once we clicked the div, the onclick event will be fired and it fetches the inner HTML of the element multiLevelTable. Once it does, we are formulating the data and assigning it to the location.href().

Please see here to understand the basic difference between the window.location.href() and window.open(): Window.location.href () and Window.open () methods in JavaScript.

Wow cool, we did it.

Export Hierarchical HTML Table

Export Hierarchical HTML Table

Figure: without style.

Export Hierarchical HTML Table

Export Hierarchical HTML Table

Figure: with style

Wait, we are not done yet.

Now what if you have many HTML tables and you may need to export all the HTML tables? Of course, we cannot create separate functions, right?

So, can we make some changes to our function?

Let us do this.

New Export Function

JavaScript
var exportThisWithParameter = (function () {
            var uri = ‘data:application/vnd.ms-excel;base64,’, 
		template = ‘<html xmlns:o="urn:schemas-microsoft-com:office:office" 
		xmlns:x="urn:schemas-microsoft-com:office:excel"  
		xmlns="http://www.w3.org/TR/REC-html40″><head> 
		<!–[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets> 
		<x:ExcelWorksheet><x:Name>{worksheet}</x:Name> 
		<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions> 
		</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook> 
		</xml><![endif]–></head><body> 
		<table>{table}</table></body></html>’,
                base64 = function (s) {
                    return window.btoa(unescape(encodeURIComponent(s)))
                },
                format = function (s, c) {
                    return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; })
                }
            return function (tableID, excelName) {
                tableID = document.getElementById(tableID)
                var ctx = { worksheet: excelName || ‘Worksheet’, table: tableID.innerHTML }
                window.location.href = uri + base64(format(template, ctx))
            }
        })()

In the preceding function, you can see the parameters (tableID, excelName). This is what we need to pass from the click event as follows:

HTML
<div onclick="exportThisWithParameter(‘multiLevelTable’, 
‘Multi Level Export Table Example’)" 
style="cursor: pointer; border: 1px solid #ccc; text-align: center;width:19%;">
Export Multi Level Table to Excel With Parameter</div>

Complete HTML

HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Export Hierarchical HTML Using JQuery – Sibeesh|Passion</title>
    <script src="Contents/jquery-1.9.1.js"></script>
    <style>
    td,th,thead,caption,tr{
        text-align:center;border:1px solid #ccc;
    }
        caption {
            background-color:#ccc;
        }
</style>
    <script type="text/javascript">
        var exportThis = (function () {
            var uri = ‘data:application/vnd.ms-excel;base64,’,
                template = ‘<html xmlns:o="urn:schemas-microsoft-com:office:office" 
		xmlns:x="urn:schemas-microsoft-com:office:excel"  
		xmlns="http://www.w3.org/TR/REC-html40″><head> 
		<!–[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets> 
		<x:ExcelWorksheet><x:Name>{worksheet}</x:Name> 
		<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions> 
		</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook> 
		</xml><![endif]–></head><body> 
		<table>{table}</table></body></html>’,
                base64 = function (s) {
                    return window.btoa(unescape(encodeURIComponent(s)))
                },
                format = function (s, c) {
                    return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; })
                }
            return function () {
                var ctx = { worksheet: ‘Multi Level Export Table Example’ || 
		‘Worksheet’, table: document.getElementById("multiLevelTable").innerHTML }
                window.location.href = uri + base64(format(template, ctx))
            }
        })()
        var exportThisWithParameter = (function () {
            var uri = ‘data:application/vnd.ms-excel;base64,’,
                template = ‘<html xmlns:o="urn:schemas-microsoft-com:office:office" 
		xmlns:x="urn:schemas-microsoft-com:office:excel"  
		xmlns="http://www.w3.org/TR/REC-html40″><head> 
		<!–[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets> 
		<x:ExcelWorksheet><x:Name>{worksheet}</x:Name> 
		<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions> 
		</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook> 
		</xml><![endif]–></head><body> 
		<table>{table}</table></body></html>’,
                base64 = function (s) {
                    return window.btoa(unescape(encodeURIComponent(s)))
                },
                format = function (s, c) {
                    return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; })
                }
            return function (tableID, excelName) {
                tableID = document.getElementById(tableID)
                var ctx = { worksheet: excelName || ‘Worksheet’, table: tableID.innerHTML }
                window.location.href = uri + base64(format(template, ctx))
            }
        })()
    </script>
</head>
<body>
    <div onclick="exportThis()" style="cursor: pointer; border: 1px solid #ccc; 
	text-align: center;width:19%;">Export Multi Level Table to Excel</div>
    <br />
    <div onclick="exportThisWithParameter(‘multiLevelTable’, 
    ‘Multi Level Export Table Example’)" 
	style="cursor: pointer; border: 1px solid #ccc; 
	text-align: center;width:19%;">Export Multi Level Table to Excel With Parameter</div>
    <br />
    <br />
    <table id="multiLevelTable">
        <caption>My Multi Level Table</caption>
        <thead>
            <tr>
                <th colspan="2" rowspan="2" 
                style="background-color:aqua;">Column 0</th>
                <th rowspan="2">Column 1</th>
                <th colspan="2">Column 2</th>
            </tr>
            <tr>
                <th>Column 2a</th>
                <th>Column 2b</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th rowspan="2">Row 1</th>
                <th>Row 1a</th>
                <td>123</td>
                <td>456</td>
                <td>789</td>
            </tr>
            <tr>
                <th>Row 1b</th>
                <td>123</td>
                <td>456</td>
                <td>789</td>
            </tr>
            <tr>
                <th colspan="2">Row 2</th>
                <td>123</td>
                <td>456</td>
                <td>789</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

Points of Interest

Hierarchical HTML, HTML, JQuery, Multi Level HTML

History

First version: 19-Jan-2015

Conclusion

That is all for the day. I hope you enjoyed this article. Thanks for reading. Please provide your valuable suggestions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)