Export HTML table to CSV using vanilla javascript
I am trying to add a feature of csv download option in my website. It should convert the html table present in the website in to csv content and make it downloadable. Ive been searching through internet for a good plugin and found some usefule ones like http://www.dev-skills.com/export-html-table-to-csv-file/ But it uses php script to do the download part. I was wondering if there is a pure javascript library available to do this feature using server side softwares like node.js without the use of php??
Solution 1:
Should work on every modern browser and without jQuery or any dependency, here my implementation :
// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ',') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Then add your download button/link :
<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>
CSV file is timedated and compatible with default Excel format.
Update after comments: Added second parameter "separator", it can be used to configure another character like ;
, it's useful if you have user downloading your csv in different region of the world because they can use another default separator for Excel, for more information see : https://superuser.com/a/606274/908273
Solution 2:
Using just jQuery
, vanilla Javascript
, and the table2CSV
library:
export-to-html-table-as-csv-file-using-jquery
Put this code into a script to be loaded in the head
section:
$(document).ready(function () {
$('table').each(function () {
var $table = $(this);
var $button = $("<button type='button'>");
$button.text("Export to spreadsheet");
$button.insertAfter($table);
$button.click(function () {
var csv = $table.table2CSV({
delivery: 'value'
});
window.location.href = 'data:text/csv;charset=UTF-8,'
+ encodeURIComponent(csv);
});
});
})
Notes:
Requires jQuery and table2CSV: Add script references to both libraries before the script above.
The table
selector is used as an example, and can be adjusted to suit your needs.
It only works in browsers with full Data URI
support: Firefox, Chrome and Opera, not in IE, which only supports Data URIs
for embedding binary image data into a page.
For full browser compatibility you would have to use a slightly different approach that requires a server side script to echo
the CSV.
Solution 3:
There is a very easy free and open source solution at http://jordiburgos.com/post/2014/excellentexport-javascript-export-to-excel-csv.html
First download the javascript file and sample files from https://github.com/jmaister/excellentexport/releases/tag/v1.4
The html page looks like below.
Make sure the the javascript file is in the same folder or change the path of the script in the html file accordingly.
<html>
<head>
<title>Export to excel test</title>
<script src="excellentexport.js"></script>
<style>
table, tr, td {
border: 1px black solid;
}
</style>
</head>
<body>
<h1>ExcellentExport.js</h1>
Check on <a href="http://jordiburgos.com">jordiburgos.com</a> and <a href="https://github.com/jmaister/excellentexport">GitHub</a>.
<h3>Test page</h3>
<br/>
<a download="somedata.xls" href="#" onclick="return ExcellentExport.excel(this, 'datatable', 'Sheet Name Here');">Export to Excel</a>
<br/>
<a download="somedata.csv" href="#" onclick="return ExcellentExport.csv(this, 'datatable');">Export to CSV</a>
<br/>
<table id="datatable">
<tr>
<th>Column 1</th>
<th>Column "cool" 2</th>
<th>Column 3</th>
</tr>
<tr>
<td>100,111</td>
<td>200</td>
<td>300</td>
</tr>
<tr>
<td>400</td>
<td>500</td>
<td>600</td>
</tr>
<tr>
<td>Text</td>
<td>More text</td>
<td>Text with
new line</td>
</tr>
</table>
</body>
It is very easy to use this as I have tried most of the other methods.
Solution 4:
You don't need PHP script on server side. Do that in the client side only, in browsers that accept Data URIs:
data:application/csv;charset=utf-8,content_encoded_as_url
The Data URI will be something like:
data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333
You can call this URI by:
- using
window.open
- or setting the
window.location
- or by the href of an anchor
- by adding the download attribute it will work in chrome, still have to test in IE.
To test, simply copy the URIs above and paste in your browser address bar. Or test the anchor below in a HTML page:
<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>
To create the content, getting the values from the table, you can use table2CSV mentioned by MelanciaUK and do:
var csv = $table.table2CSV({delivery:'value'});
window.location.href = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(csv);