Demo
See below for an explanation.
$(document).ready(function() {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function(i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function(j, col) {
var $col = $(col),
text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"';
// Deliberate 'false', see comment below
if (false && window.navigator.msSaveBlob) {
var blob = new Blob([decodeURIComponent(csv)], {
type: 'text/csv;charset=utf8'
});
// Crashes in IE 10, IE 11 and Microsoft Edge
// See MS Edge Issue #10396033
// Hence, the deliberate 'false'
// This is here just for completeness
// Remove the 'false' at your own risk
window.navigator.msSaveBlob(blob, filename);
} else if (window.Blob && window.URL) {
// HTML5 Blob
var blob = new Blob([csv], {
type: 'text/csv;charset=utf-8'
});
var csvUrl = URL.createObjectURL(blob);
$(this)
.attr({
'download': filename,
'href': csvUrl
});
} else {
// Data URI
var csvData="data:application/csv;charset=utf-8," + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
}
// This must be a hyperlink
$(".export").on('click', function(event) {
// CSV
var args = [$('#dvData>table'), 'export.csv'];
exportTableToCSV.apply(this, args);
// If CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
a.export,
a.export:visited {
display: inline-block;
text-decoration: none;
color: #000;
background-color: #ddd;
border: 1px solid #ccc;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="export">Export Table data into Excel</a>
<div id="dvData">
<table>
<tr>
<th>Column One</th>
<th>Column Two</th>
<th>Column Three</th>
</tr>
<tr>
<td>row1 Col1</td>
<td>row1 Col2</td>
<td>row1 Col3</td>
</tr>
<tr>
<td>row2 Col1</td>
<td>row2 Col2</td>
<td>row2 Col3</td>
</tr>
<tr>
<td>row3 Col1</td>
<td>row3 Col2</td>
<td>row3 Col3</td>
</tr>
<tr>
<td>row4 'Col1'</td>
<td>row4 'Col2'</td>
<td>row4 'Col3'</td>
</tr>
<tr>
<td>row5 "Col1"</td>
<td>row5 "Col2"</td>
<td>row5 "Col3"</td>
</tr>
<tr>
<td>row6 "Col1"</td>
<td>row6 "Col2"</td>
<td>row6 "Col3"</td>
</tr>
</table>
</div>
As of 2017
Now uses HTML5 Blob
and URL
as the preferred method with Data URI
as a fallback.
On Internet Explorer
Other answers suggest window.navigator.msSaveBlob
; however, it is known to crash IE10/Window 7 and IE11/Windows 10. Whether it works using Microsoft Edge is dubious (see Microsoft Edge issue ticket #10396033).
Merely calling this in Microsoft’s own Developer Tools / Console causes the browser to crash:
navigator.msSaveBlob(new Blob(["hello"], {type: "text/plain"}), "test.txt");
â¨Four years after my first answer, new IE versions include IE10, IE11, and Edge. They all crash on a function that Microsoft invented (slow clap).
Add
navigator.msSaveBlob
support at your own risk.
As of 2013
Typically this would be performed using a server-side solution, but this is my attempt at a client-side solution. Simply dumping HTML as a Data URI
will not work, but is a helpful step. So:
- Convert the table contents into a valid CSV formatted string. (This is the easy part.)
- Force the browser to download it. The
window.open
approach would not work in Firefox, so I used<a href="https://stackoverflow.com/questions/16078544/{Data URI here}">
. - Assign a default file name using the
<a>
tag’sdownload
attribute, which only works in Firefox and Google Chrome. Since it is just an attribute, it degrades gracefully.
Notes
- You can style your link to look like a button. I’ll leave this effort to you
- IE has Data URI restrictions. See: Data URI scheme and Internet Explorer 9 Errors
-
About the “download” attribute, see these:
Compatibility
Browsers testing includes:
- Firefox 20+, Win/Mac (works)
- Google Chrome 26+, Win/Mac (works)
- Safari 6, Mac (works, but filename is ignored)
- IE 9+ (fails)
Content Encoding
The CSV is exported correctly, but when imported into Excel, the character ü
is printed out as ä
. Excel interprets the value incorrectly.
Introduce var csv = '\ufeff';
and then Excel 2013+ interprets the values correctly.
If you need compatibility with Excel 2007, add UTF-8 prefixes at each data value. See also: