Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Any HTML table that you have created can be converted into an Excel Spreadsheet by using jQuery and it is compatible with all browsers. There are two simple approaches that require basic HTML and jQuery knowledge to achieve this.
- Approach 1: Using jQuery plugin: A simple jQuery plugin ‘table2excel’ can be used for converting an HTML table to an excel sheet.
Syntax:
$("#table-id").table2excel({ filename: "excel_sheet-name.xls" });
- Example:
html
<
table
id="studtable">
<
tr
>
<
th
>ID</
th
>
<
th
>Name</
th
>
<
th
>Age</
th
>
<
th
>Address</
th
>
</
tr
>
<
tr
>
<
td
>101</
td
>
<
td
>Alex</
td
>
<
td
>15</
td
>
<
td
>Maldives</
td
>
</
tr
>
<
tr
>
<
td
>102</
td
>
<
td
>Chris</
td
>
<
td
>14</
td
>
<
td
>Canada</
td
>
</
tr
>
<
tr
>
<
td
>103</
td
>
<
td
>Jay</
td
>
<
td
>15</
td
>
<
td
>Toronto</
td
>
</
tr
>
</
table
>
<
script
>
$(document).ready(function () {
$("#studtable").table2excel({
filename: "Students.xls"
});
});
</
script
>
- Output:
ID Name Age Address 101 Alex 15 Maldives 102 Chris 14 Canada 103 Jay 15 Toronto
- The above output gets converted into an Excel spreadsheet in the exact same manner the HTML table is. About ‘table2excel’: The ‘table2excel’ is a simple yet useful jQuery plugin that allows for exporting HTML table data to an Excel file. The ‘table2excel’ also has a feature to exclude cells that contain a specified class. Syntax for noExport:
$(document).ready(function() { $("#table-id").table2excel({ exclude: ".noExport", filename: "name-of-the-file", }); });
- Example code for excluding some specified cells:
html
<
script
src=
"//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">
</
script
>
<
script
src=
"//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js">
</
script
>
<
button
>Export</
button
>
<
table
>
<
thead
>
<
tr
>
<
td
class="noExport">
This cell will not be exported.
</
td
>
<
td
>
This cell will get exported.
</
td
>
</
tr
>
</
thead
>
<
tbody
>
<
tr
>
<
td
>Alex</
td
>
<
td
class="noExport">Maldives</
td
>
</
tr
>
<
tr
>
<
td
>Chris</
td
>
<
td
>Canada</
td
>
</
tr
>
</
tbody
>
</
table
>
- Note: In the above sample code, the class ‘.noExport’ has been used to exclude those specified cells from the HTML table data. Therefore the exported Excel Spreadsheet also does not include those cells from the HTML table data.
- Approach 2: Using simple HTML: Consider the same students table above to understand the below. Let’s use a button in our code which when clicked to converts the HTML data table into an Excel spreadsheet. Note that the ‘export’ button below does not actually convert the HTML table to an excel sheet. This has to used in a proper and already existing HTML code to get the Excel spreadsheet and will not work in this IDE.
html
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
HTML Table To Excel
spreadsheet using
HTML only
</
title
>
</
head
>
<
body
>
<
table
id="studtable">
<
tr
>
<
th
>ID</
th
>
<
th
>Name</
th
>
<
th
>Age</
th
>
<
th
>Address</
th
>
</
tr
>
<
tr
>
<
td
>101</
td
>
<
td
>Alex</
td
>
<
td
>15</
td
>
<
td
>Maldives</
td
>
</
tr
>
<
tr
>
<
td
>102</
td
>
<
td
>Chris</
td
>
<
td
>14</
td
>
<
td
>Canada</
td
>
</
tr
>
<
tr
>
<
td
>103</
td
>
<
td
>Jay</
td
>
<
td
>15</
td
>
<
td
>Toronto</
td
>
</
tr
>
</
table
>
<
button
onclick="tableToExcel(
'studtable', 'Students')">
Click to Export
</
button
>
</
body
>
</
html
>
- Output:
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps. jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more“.
- HTML Tutorial and HTML Examples.
- jQuery Tutorial and jQuery Examples.
Like Article
Save Article
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>jQuery table2excel plugin</
title
>
<
script
src
=
</
script
>
<
script
src
=
"jquery.table2excel.js"
></
script
>
</
head
>
<
body
>
<
h1
style
=
"color:green"
>GeeksForGeeks</
h1
>
<
b
>jQuery table2excel plugin </
b
>
<
p
></
p
>
<
table
class
=
"table2excel"
>
<
thead
>
<
tr
class
=
"noExl"
>
<
td
>
Table 1 Header, column 1 (not exported)</
td
>
<
td
>Table 1 Header, column 2(not exported)
</
td
>
</
tr
>
<
tr
><
td
>Table 1 Header, column 1 (exported)</
td
>
<
td
>Table 1 Header, column 2 (exported)</
td
></
tr
>
</
thead
>
<
tbody
>
<
tr
><
td
>Row 1, column 1 data of table1</
td
>
<
td
>Row 1 column 2 data of table 1</
td
></
tr
>
<
tr
><
td
>Row 2, column 1 data of table1</
td
>
<
td
>Row 2, column 2 dataof table1</
td
></
tr
>
</
tbody
>
<
tfoot
>
<
tr
><
td
colspan
=
"2"
>This is the footer of table 1.</
td
></
tr
>
</
tfoot
>
</
table
>
<
button
class
=
"exportBtnClass"
>Export to XLS file</
button
><
p
></
p
>
<
table
class
=
"table2excel colorClass"
>
<
thead
>
<
tr
class
=
"noExl"
>
<
td
>Table 2 Header, column 1 (not exported)</
td
>
<
td
>Table 2 Header, column 1 (not exported)</
td
></
tr
>
<
tr
><
td
style
=
"background-color: green;"
>
Table 2 Header, column 1 (exported with colors)</
td
>
<
td
>Table 2 Header, column 2 (exported)</
td
></
tr
>
</
thead
>
<
tbody
>
<
tr
><
td
style
=
"background-color: red;"
>
Row 1, column 1 data of table2</
td
>
<
td
>Row 1 column 2 data of table2</
td
></
tr
>
<
tr
><
td
>Row 2, column 1 data of table2</
td
>
<
td
>Row 2, column 2 data of table2</
td
></
tr
>
</
tbody
>
<
tfoot
>
<
tr
><
td
colspan
=
"2"
>
This is the footer of table 2</
td
></
tr
>
</
tfoot
>
</
table
>
<
button
class
=
"exportBtnClass"
>
Export to XLS file
</
button
>
<
script
>
$(function() {
$(".exportBtnClass").click(function(e){
var table = $(this).prev('.table2excel');
if(table && table.length){
var preserveColors =
(table.hasClass('colorClass') ? true : false);
$(table).table2excel({
// This class's content is excluded from getting exported
exclude: ".noExl",
name: "Output excel file ",
filename:
"outputFile-" + new Date().toString().replace(/[-:.]/g, "") + ".xls",
fileext: ".xls", //File extension type
exclude_img: true,
exclude_links: true,
exclude_inputs: true,
preserveColors: preserveColors
});
}
});
});
</
script
>
</
body
>
</
html
>
The reason the solution you found on the internet is no working is because of the line that starts var colCount
. The variable mytable
only has two elements being <thead>
and <tbody>
. The var colCount
line is looking for all the elements within mytable
that are <tr>
. The best thing you can do is give an id to your <thead>
and <tbody>
and then grab all the values based on that. Say you had <thead id='headers'>
:
function write_headers_to_excel()
{
str="";
var myTableHead = document.getElementById('headers');
var rowCount = myTableHead.rows.length;
var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for(var i=0; i<rowCount; i++)
{
for(var j=0; j<colCount; j++)
{
str= myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
}
}
}
and then do the same thing for the <tbody>
tag.
EDIT: I would also highly recommend using jQuery. It would shorten this up to:
function write_to_excel()
{
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
$('th, td').each(function(i){
ExcelSheet.ActiveSheet.Cells(i+1,i+1).Value = this.innerHTML;
});
}
Now, of course, this is going to give you some formatting issues but you can work out how you want it formatted in Excel.
EDIT: To answer your question about how to do this for n
number of tables, the jQuery will do this already. To do it in raw Javascript, grab all the tables and then alter the function to be able to pass in the table as a parameter. For instance:
var tables = document.getElementsByTagName('table');
for(var i = 0; i < tables.length; i++)
{
write_headers_to_excel(tables[i]);
write_bodies_to_excel(tables[i]);
}
Then change the function write_headers_to_excel()
to function write_headers_to_excel(table)
. Then change var myTableHead = document.getElementById('headers');
to var myTableHead = table.getElementsByTagName('thead')[0];
. Same with your write_bodies_to_excel()
or however you want to set that up.
jQuery table2excel Plugin (https://github.com/rainabba/jquery-table2excel)
#Credit for the core table export code concept goes to insin (met on Freenode in #javascript) and core code inspired from https://gist.github.com/insin/1031969
FIRST!!
Thanks for your interest. I haven’t been able to maintain this and found the following project which looks well ahead of this one, so you may want to consider it first: TableExport
DISCLAIMER
This plugin is a hack on a hack. The .xls extension is the only way [some versions] of excel will even open it, and you will get a warning about the contents which can be ignored. The plugin was developed against Chrome and other have contributed code that should allow it to work in Firefox and Safari, but inconsistently since it’s a hack that’s not well supported anywhere but Chrome. I would not use this in public production personally and it was developed for an Intranet application where users are on Chrome and had known versions of Excel installed and the users were educated about the warning. These users also save-as in Excel so that when the files are distributed, the end-users don’t get the warning message.
Install — Bower
Install bower
globally
Install jquery-table2excel and dependencies
bower install jquery-table2excel --save
Include jquery and table2excel in your page
<script src="bower_componentsjquerydistjquery.min.js"></script> <script src="bower_componentsjquery-table2exceldistjquery.table2excel.min.js"></script>
Install — Legacy
Include jQuery and table2excel plugin:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script>
Using the plugin
$("#yourHtmTable").table2excel({ exclude: ".excludeThisClass", name: "Worksheet Name", filename: "SomeFile.xls", // do include extension preserveColors: false // set to true if you want background colors and font colors preserved });
demo/
Contains a simple HTML file to demonstrate your plugin.
dist/
This is where the generated files are stored once Grunt runs.
.editorconfig
This file is for unifying the coding style for different editors and IDEs.
Check editorconfig.org if you haven’t heard about this project yet.
.jshintrc
List of rules used by JSHint to detect errors and potential problems in JavaScript.
Check jshint.com if you haven’t heard about this project yet.
.travis.yml
Definitions for continous integration using Travis.
Check travis-ci.org if you haven’t heard about this project yet.
table2excel.jquery.json
Package manifest file used to publish plugins in jQuery Plugin Registry.
Check this Package Manifest Guide for more details.
Gruntfile.js
Contains all automated tasks using Grunt.
Check gruntjs.com if you haven’t heard about this project yet.
package.json
Specify all dependencies loaded via Node.JS.
Check NPM for more details.
Contributing
Check CONTRIBUTING.md
History
Check Release list.
License
MIT License
Introduction
This assumes basic familiarity with DataTables, its buttons extension, and the related ability to export table data to various file formats, including Excel.
I already wrote some overview notes here, but this is a large subject, and needs a bit more space.
Here, I will focus on reference material which is useful when you want to customize Excel exports.
More specifically I will only consider Office Open XML (.xlsx
) files. Older .xls
files (up to Excel 2003) use a different format and are not considered here.
Excel File Structure
The official Microsoft reference documentation for Excel file structures is here:
Excel (.xlsx) Extensions to the Office Open XML SpreadsheetML File Format
The underlying standards on which the above extensions are based can be found here:
ECMA-376 — Office Open XML file formats
In a nutshell, an Excel file is a zip file containing a series of sub-folders and XML documents.
Using Open Office nomenclature, the zip file is a “package” which contains “parts” (the XML files) and optionally other files such as graphics files.
We will look at a very simplified version of that structure, as used by DataTables:
|
|
DataTables builds a default Excel file from a series of XML strings hard-coded into the following JavaScript resource:
https://cdn.datatables.net/buttons/1.6.5/js/buttons.html5.js
Search for var excelStrings
to see these for yourself. Here you will see, for example, the 68 predefined built-in cell styles which you can refer to when exporting DataTables data.
Content Types
The [Content_Types].xml
file contains a list of the different parts in the package, together with each part’s type — for example:
|
|
Relationships
The _rels.rels
file contains a set of relationship IDs. These are then used to define the relationships between different parts in the package.
As well as the top-level .rels
file, there can be others — such as the workbook.xml.rels
file shown above, which can contain relationships to the other parts of the overall content, such as sheet1.xml
, sharedStrings.xml
, styles.xml
, and so on.
An example is:
|
|
Workbook
The workbook.xml
file contains a list of worksheets:
|
|
Here we can see the rId1
relationship ID being used.
Styles
The styles.xml
file contains information relating to fonts, borders, fills, alignment, and so on. These can then be re-used in different locations.
An example:
|
|
Worksheets
The sheet1.xml
file contains worksheet data:
|
|
Rows and Cells
In a row such as the following:
|
|
The meanings for each part are as follows:
Item | Description |
---|---|
<row> |
a row |
r="13" |
row 13 |
<c> |
cell tag |
r="A13" |
cell reference A13 |
s="12" |
the cell’s formatting is at <xf> index 12 in the <cellXfs> formatting list |
t="s" |
the t type attribute for the cell, where s means “shared strings”, where the text is stored. |
<v="25"/> |
the string’s index is 25 — it’s the 26th string in the shared strings list. |
List of t
types:
Type | Description |
---|---|
b |
boolean |
d |
date |
e |
error |
inlineStr |
an inline string (i.e., not stored in the shared strings part, but directly in the cell) |
n |
number, stored directly in the cell |
s |
shared string (so stored in the shared strings part and not in the cell) |
str |
a formula (a string representing the formula) |
The following example shows a cell (B2) containing the number 400, stored in the cell itself:
|
|
The above is just a small sample of the possible configuration options supported by Excel.
Documentation
Excel Options
The following page lists the main options which can be attached to an Excep export button.
https://datatables.net/reference/button/excel
Items of note are:
customize: function( xlsx ) { ... }
— provides low-level access to the Excel file, where customizations can be made — typically by direct manipulation of the XML structures described in earlier sections of this post.exportOptions
— see theexportData
section below for details.filename
andextension
— for the Excel file.header
andfooter
— whether or not to include the table’s header and footer.messageTop
andmessageBottom
— additional line of data to be included in the spreadsheet.sheetName
— Excel sheet name.title
— added to the Excel sheet. See theexportInfo
section below for details.
Example:
|
|
Here, options such as filename
can also be functions:
|
|
Exported Data
The following page covers various ways to control what specific data is exported from the DataTable to Excel.
https://datatables.net/reference/api/buttons.exportData()
If the export options are provided as part of the DataTable button configuration, then you use the exportOptions: { ... }
option referred to in the previous section.
If you use this as a standalone processor, then you use the exportData( { ... } )
function as follows:
|
|
Items of note are:
rows
— a row selector.columns
— a column selector.orthogonal
— what orthogonal data to include.stripHtml
— strips HTML by default.stripNewlines
— stripts newlines by default.format
— various cell formatting functions — see below.
For the format
option, you can provide various functions as follows:
|
|
Items of note:
header (innerHTML, colIdx, node)
— format the header data.footer (innerHTML, colIdx, node)
— format the footer data.body (innerHTML, rowIdx, colIdx, node)
— format the body data.customizeData (data)
— a final chance to customize the overall data. Mutate thedata
object which contains aheader
array, afooter
array and abody
2D array. No return value is used.
Export Info
The following page covers options which may be common to multiple buttons for one table:
https://datatables.net/reference/api/buttons.exportInfo()
As such, the options available here overlap with some of those presented in the “Excel Options” section above — for example:
filename
andextension
— for the Excel file.messageTop
andmessageBottom
— additional line of data to be included in the spreadsheet.title
— added to the Excel sheet. By default, this will use the web page’s<title>
value.
This is generally used outside of a button or with a custom button.
Low-Level Changes
Consider the following button option:
|
|
This accesses the underlying XML data for the Excel worksheet. It then uses jQuery to select the text content of cell A1. Finally it updates that content.
Some other examples:
Change row 1’s formatting:
|
|
NOTE: As of jQuery 3.4, the :first
pseudo-class is deprecated. Remove it from your selectors and filter the results later using .first()
.
Change row 3’s formatting:
|
|
Change column B’s formatting:
|
|
WARNING — if your spreadsheet has sufficient columns, you may find this also selects column BA, BB, and so on.
Change any row where the row number contains a 3 (3, 13, 23, 30, 31…):
|
|
Get the last column in the sheet:
|
|
Here is an example which preserves very long numbers as text (and not, for example, as numbers in scientific notation):
https://stackoverflow.com/a/52047216/12567365
Here is an example which adds a new cell formatter:
|
|
The following example shows the creation of additional sheets in the Excel file created from Datatables:
https://gist.github.com/northcoder-repo/05bde971c7879ea5ebc4907f323376fc
Custom Buttons
You can create completely customized buttons:
https://datatables.net/extensions/buttons/custom
https://datatables.net/reference/option/buttons.buttons.action
Consider this:
$.fn.DataTable.ext.buttons.excelHtml5.action.call(that, e, dt, node, config);
It uses the JavaScript call()
method to call a function.
As used here, it allows us to provide a customized “please wait” pop-up modal (Swal
is SweetAlert2):
|
|