ExcellentExport.js
-
❤️ Sponsor ExcellentExport.js project❤️
-
JavaScript export to Excel or CSV.
-
A quick JavaScript library to create export to Excel/CSV from HTML tables in the browser. No server required.
-
As part of the new version 3.0.0+, there is support for XLSX. The drawback is that the library is 200+ KB.
-
Check My Blog Page for Testing :
JavaScript export to ExcelExcellentExport.js update: JavaScript export to Excel and CSV
Revision history:
3.9.3
- Fix TypeScript exported types
3.9.0
- Cell types and formats!!! Now you can define the cell type and format. For example, you can define a cell as a date or a number. You can also define the format of the cell. For example, you can define a cell as a date with the format «dd/mm/yyyy» or a number with the format «#,##0.00».
3.8.1
- Activate XLSX compression by default. The example of index.bigtable.html went from 18Mb to 3Mb.
- Update npm dependencies to fix vulnerabilities
- Update to latest version of TypeScript
- Reduced size of the library from 912 KB to 277 KB!!!
3.8.0
- Allow RTL options on the whole file or sheet.
- Update npm dependencies to fix vulnerabilities
3.7.3
- Fix (#591) remove columns parameter. Now it is not affected by repeated column numbers nor its order.
3.7.2
- Update npm dependencies to fix vulnerabilities
3.7.1
- Update npm dependencies to fix vulnerabilities
- Start using Dependabot and get rid of Dependabot-preview
3.7.0
- Added option
openAsDownload: boolean
. Use this option to download as a file without using an anchor tag. So download can be triggered from a button. - Update npm dependencies to fix vulnerabilities
3.6.0
- Added sponsor link to the project ❤️ Sponsor ExcellentExport.js project❤️
- Transform the project from JavaScript to TypeScript
- Configure Jest as test runner
- Update npm dependencies to fix vulnerabilities
3.5.0
- Add fixValue and fixArray functions to configuration: these configuration functions can be used to manipulate the values of the cells.
- Update npm dependencies to fix vulnerabilities
3.4.3
- Update npm dependencies to fix vulnerabilities
3.4.2
- Remove ES6 function syntax to support IE11
- Update npm dependencies to fix vulnerabilities
3.4.0
- Configure TravisCI on GitHub
- Update npm dependencies to fix vulnerabilities
3.3.0
- Remove columns by index
- Filter rows by value
- Updated build to Webpack 4.x.x
3.2.1
- Update npm dependencies to fix vulnerabilities
3.2.0
- Update npm dependencies to fix vulnerabilities
3.1.0
- Fix old API for base64 and escaping problem.
3.0.0
- XLSX support. This bumps the build size to 640 KB.
- New API : ExcellentExport.convert(…)
- Autogenerate download filename.
- Data input from arrays or HTML Tables.
- Multiple sheets for XLS or XLSX formats.
2.1.0
- Add Webpack build.
- Create UMD JavaScript module. Library can be loaded as a module (import, RequireJS, AMD, etc…) or standalone as window.ExcelentExport.
2.0.3
- Fix export as a module.
- Changed minifier to UglifyJS.
2.0.2
- Fix CSV Chinese characters and other special characters display error in Windows Excel.
- Fix URL.createObjectURL(…) on Firefox.
2.0.0
- Now it can export to big files +2MB.
- Minimum IE 11.
- Links open with URL.createObjectURL(…).
- NPM package available.
- Using Semantic versioning (2.0.0 instead of 2.0).
- Module can be loaded standalone or with RequireJS.
- Change license to MIT.
1.5
- Possibility to select a CSV delimiter.
- Bower package available.
- Compose package available.
1.4
- Add LICENSE.txt with GPL v3
- UTF-8 characters fixed.
1.3
- Added minified version
1.1
- Added CSV data export
1.0
- Added Excel data export
Compatibility
- Firefox
- Chrome
- Internet Explorer 11+
Install
npm
npm install excellentexport --save
yarn
bower
bower install excellentexport
Load
Include script in your HTML:
<script type="text/javascript" src="dist/excellentexport.js"></script>
Include script in your HTML using CDN:
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/excellentexport@3.4.3/dist/excellentexport.min.js"></script>
Require.js
<script src="http://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
<script>
require(['dist/excellentexport'], function(ee) {
window.ExcellentExport = ee;
});
</script>
ES6 import
import ExcellentExport from 'excellentexport';
Usage
<table id="datatable">
<tr>
<td>100</td> <td>200</td> <td>300</td>
</tr>
<tr>
<td>400</td> <td>500</td> <td>600</td>
</tr>
</table>
<a download="somedata.xls" href="#" onclick="return ExcellentExport.excel(this, 'datatable', 'Sheet Name Here');">Export to Excel</a>
<a download="somedata.csv" href="#" onclick="return ExcellentExport.csv(this, 'datatable');">Export to CSV</a>
<!-- new API, xlsx -->
<a download="somedata.xlsx" href="#" onclick="return ExcellentExport.convert({ anchor: this, filename: 'data_123.array', format: 'xlsx'},[{name: 'Sheet Name Here 1', from: {table: 'datatable'}}]);">Export to CSV</a>
API
ExcellentExport.convert(options, sheets);
Options:
{
anchor: String or HTML Element,
format: 'xlsx' or 'xls' or 'csv',
filename: String,
rtl: Use Right-to-left characters, boolean (optional)
}
Sheets must be an array of sheet configuration objects. Sheet description:
[
{
name: 'Sheet 1', // Sheet name
from: {
table: String/Element, // Table ID or table element
array: [...] // Array with the data. Array where each element is a row. Every row is an array of the cells.
},
removeColumns: [...], // Array of column indexes (from 0)
filterRowFn: function(row) {return true}, // Function to decide which rows are returned
fixValue: function(value, row, column) {return fixedValue} // Function to fix values, receiving value, row num, column num
fixArray: function(array) {return array} // Function to manipulate the whole data array
rtl: Use Right-to-left characters, boolean (optional)
formats: [...] // Array of formats for each column. See formats below.
...
},
{
...
}, ...
]
fixValue example
This is an example for the fixValue function to handle HTML tags inside a table cell.
It transforms BR to line breaks and then strips all the HTML tags.
fixValue: (value, row, col) => {
let v = value.replace(/<br>/gi, "n");
let strippedString = v.replace(/(<([^>]+)>)/gi, "");
return strippedString;
}
Formats
You can specify an array with the formats for a specific cell range (i.e. A1:A100, A1:D100, A1:H1, etc).
Each element in the format array consists on:
{ "range": "A1:A100", // Range of cells to apply the format, mandatory "format": { "type": "<cell_type>", // Type of format, mandatory "pattern": "<pattern>" // Pattern, optional } }
Example:
formats: [ { range: "C2:C20", format: { type: "n", pattern: "0.00", }, }, { range: "C2:C20", format: ExcellentExport.formats.NUMBER, } ],
format
can be used from one of the predefined types if you use TypeScript
cell_type
can be one of the followint:
's': String
'n': Number
'd': Date
'b': Boolean
pattern
is a string with the format pattern used in Excel. For example:
'0' // Integer
'0.00' // 2 decimals
'dd/mm/yyyy' // Date
'dd/mm/yyyy hh:mm:ss' // Date and time
'0.00%' // Percentage
'0.00e+00' // Scientific notation
'@' // Text
Notes
- IE8 or lower do not support data: url schema.
- IE9 does not support data: url schema on links.
- IE10 and above and Edge are supported via the Microsoft-specific
msOpenOrSaveBlob
method.
Test
python 2.x:
python -m SimpleHTTPServer 8000
python 3.x:
python -m http.server 8000
Build
Install dependencies:
Build development version dist/excellentexport.js
Build publish version of dist/excellentexport.js
Publish
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.
- Home
- JavaScript
- Export HTML Table Data to Excel using JavaScript
By: CodexWorld
|
In: JavaScript
|
Last Updated: Jun 7, 2021
Export data to Excel is very useful on the data list for nearly every web application. The export feature helps to download the data list as a file format for offline use. Excel format is ideal for exporting data in a file. Mostly the server-side method is used for export data to excel using PHP. But if you want a client-side solution to export table data to excel, it can be easily done using JavaScript.
The client-side export functionality makes the web application user-friendly. Using JavaScript, the HTML table data can be easily exported without page refresh. In this tutorial, we will show you how to export HTML table data to excel using JavaScript. The JavaScript export functionality can be used in the member list, product list, or other lists to download the data list in excel file format.
Export HTML Table Data to Excel
JavaScript Code:
The exportTableToExcel() function convert HTML table data to excel and download as XLS file (.xls).
tableID
– Required. Specify the HTML table ID to export data from.filename
– Optional. Specify the file name to download excel data.
function exportTableToExcel(tableID, filename = ''){ var downloadLink; var dataType = 'application/vnd.ms-excel'; var tableSelect = document.getElementById(tableID); var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20'); // Specify file name filename = filename?filename+'.xls':'excel_data.xls'; // Create download link element downloadLink = document.createElement("a"); document.body.appendChild(downloadLink); if(navigator.msSaveOrOpenBlob){ var blob = new Blob(['ufeff', tableHTML], { type: dataType }); navigator.msSaveOrOpenBlob( blob, filename); }else{ // Create a link to the file downloadLink.href = 'data:' + dataType + ', ' + tableHTML; // Setting the file name downloadLink.download = filename; //triggering the function downloadLink.click(); } }
HTML Table Data:
The HTML table contains some users data with some basic fields like name, email, country.
<table id="tblData"> <tr> <th>Name</th> <th>Email</th> <th>Country</th> </tr> <tr> <td>John Doe</td> <td>john@gmail.com</td> <td>USA</td> </tr> <tr> <td>Michael Addison</td> <td>michael@gmail.com</td> <td>UK</td> </tr> <tr> <td>Sam Farmer</td> <td>sam@gmail.com</td> <td>France</td> </tr> </table>
The button triggers exportTableToExcel() function to export HTML table data using JavaScript.
<button onclick="exportTableToExcel('tblData')">Export Table Data To Excel File</button>
If you want to export data with the custom file name, pass your desired file name in the exportTableToExcel()
function.
<button onclick="exportTableToExcel('tblData', 'members-data')">Export Table Data To Excel File</button>
Export Data to Excel in PHP
Conclusion
Our example code helps you to add export functionality in the HTML table without any third-party jQuery plugin or server-side script. You can easily export the table data using minimal JavaScript code. Also, the functionality of the example code can be enhanced or customized easily as per your needs.
- DataTables
- Excel
- Export
- JavaScript
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question
RELATED TUTORIALS
Leave a reply
Exporting data to Excel is very useful for every enterprise on data list web application. Every time , export data using custom export feature helps to download table data list for offline use as excel file like csv format. As a web Developer, I was required to do that in various live project. Excel format for exporting data in file is ideal in every enterprises. Mostly we used server-side method to export data to excel using php. But if you want to download table data to excel using client-side view then it can be easily done using javascript.
Looking for assistance with Excel assignments?
You should visit https://assignmentcore.com/excel-homework/ and get MS Excel homework help online from a team of experts.
In this tutorials, we will learn about how to export HTML table data to excel using client-side JavaScript. The Client-side export data functionality makes any web application more user-friendly. Using JavaScript, we can export or download HTML table data in excel format without page refresh.
HTMl Table Data:
The Following below HTML Table contains some user data with some basic fields like Name, Email, Age, Mobile.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<table id=«tblexportData»> <tr> <th>Name</th> <th>Email</th> <th>Age</th> <th>Mobile</th> </tr> <tr> <td>Robert</td> <td>robert@gmail.com</td> <td>26</td> <td>9999999999</td> </tr> <tr> <td>Michael</td> <td>michael@gmail.com</td> <td>24</td> <td>9999999999</td> </tr> <tr> <td>Julie</td> <td>julie@gmail.com</td> <td>36</td> <td>9999999999</td> </tr> <tr> <td>Trevor</td> <td>trevor@gmail.com</td> <td>28</td> <td>9999999999</td> </tr> </table> |
JavaScript Code:
The exportToExcel() function will use convert HTML table data to excel and download as xls file(.xls).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<script type=«text/javascript»> function exportToExcel(tableID, filename = »){ var downloadurl; var dataFileType = ‘application/vnd.ms-excel’; var tableSelect = document.getElementById(tableID); var tableHTMLData = tableSelect.outerHTML.replace(/ /g, ‘%20’); // Specify file name filename = filename?filename+‘.xls’:‘export_excel_data.xls’; // Create download link element downloadurl = document.createElement(«a»); document.body.appendChild(downloadurl); if(navigator.msSaveOrOpenBlob){ var blob = new Blob([‘ufeff’, tableHTMLData], { type: dataFileType }); navigator.msSaveOrOpenBlob( blob, filename); }else{ // Create a link to the file downloadurl.href = ‘data:’ + dataFileType + ‘, ‘ + tableHTMLData; // Setting the file name downloadurl.download = filename; //triggering the function downloadurl.click(); } } </script> |
tableID – Required. Specify the HTML table ID to export data from.
filename – Optional. Specify the file name to download excel data.
<button onclick=«exportToExcel(‘tblexportData’)»>Export Table Data To Excel File</button> |
The above button triggers exportToExcel() function to download HTML table data using javascript
If you want to download or export data with custom file name then you can pass your file name in the exportToExcel() function, see below button code:
<button onclick=«exportToExcel(‘tblexportData’, ‘user-data’)»>Export Table Data To Excel File</button> |
Complete Code:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
<html> <head> <title>Export HTML Table Data to Excel using JavaScript | Tutorialswebsite</title> <link rel=«stylesheet» href=«https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css» > <script type=«text/javascript»> function exportToExcel(tableID, filename = »){ var downloadurl; var dataFileType = ‘application/vnd.ms-excel’; var tableSelect = document.getElementById(tableID); var tableHTMLData = tableSelect.outerHTML.replace(/ /g, ‘%20’); // Specify file name filename = filename?filename+‘.xls’:‘export_excel_data.xls’; // Create download link element downloadurl = document.createElement(«a»); document.body.appendChild(downloadurl); if(navigator.msSaveOrOpenBlob){ var blob = new Blob([‘ufeff’, tableHTMLData], { type: dataFileType }); navigator.msSaveOrOpenBlob( blob, filename); }else{ // Create a link to the file downloadurl.href = ‘data:’ + dataFileType + ‘, ‘ + tableHTMLData; // Setting the file name downloadurl.download = filename; //triggering the function downloadurl.click(); } } </script> </head> <body> <div class=«container»> <table id=«tblexportData» class=«table»> <thead> <tr> <th>Name</th> <th>Email</th> <th>Age</th> <th>Mobile</th> </tr> </thead> <tbody> <tr> <td>Robert</td> <td>robert@gmail.com</td> <td>26</td> <td>9999999999</td> </tr> <tr> <td>Michael</td> <td>michael@gmail.com</td> <td>24</td> <td>9999999999</td> </tr> <tr> <td>Julie</td> <td>julie@gmail.com</td> <td>36</td> <td>9999999999</td> </tr> <tr> <td>Trevor</td> <td>trevor@gmail.com</td> <td>28</td> <td>9999999999</td> </tr> </tbody> </table> <button onclick=«exportToExcel(‘tblexportData’, ‘user-data’)» class=«btn btn-success»>Export Table Data To Excel File</button> </div> </body> </html> |
Conclusion
Our example code will help you to easily export the table data using minimal javascript code.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co