Easy HTML Table to CSV
=======================
Note:
I have modified the function to better handle malformed tables.
Features:
- Include table header rows
- Handle tables with the header rows at the bottom
- Replace with a space character
Refs:
- The `exportTableToCSV` function is from [terryyounghk's](http://jsfiddle.net/terryyounghk/KPEGU/) response to a StackOverflow question.
- The `replaceNbsps` function is from [Tim Down's answer](http://stackoverflow.com/a/1496863)
//http://stackoverflow.com/a/1496863
function replaceNbsps(str) {
var re = new RegExp(String.fromCharCode(160), "g");
return str.replace(re, " ");
}
//http://jsfiddle.net/terryyounghk/KPEGU/
function _rows2csv($rows) {
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
var tmpColDelim = String.fromCharCode(11); // vertical tab character
var tmpRowDelim = String.fromCharCode(0); // null character
// actual delimiter characters for CSV format
var colDelim = '","';
var rowDelim = '"\r\n"';
return '"' + $rows.map(function (i, row) {
var $row = $(row);
var $cols = $row.find('td,th');
return $cols.map(function (j, col) {
var $col = $(col);
var text = $col.text();
var a = text.replace('"', '""');
// escape double quotes
return replaceNbsps(a);
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"\r\n';
}
function exportTableToCSV($table, filename) {
var $bodyrows = $table.find('tr:has(td)');
var $headrows = $table.find('tr:has(th)');
// Grab text from table into CSV formatted string
var csv = _rows2csv($headrows);
csv += _rows2csv($bodyrows);
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this).attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="html2csv.js"></script>
<script type="text/javascript">
// This must be a hyperlink
$("#export").click(function (event) {
console.log(typeof exportTableToCSV);
// CSV
exportTableToCSV.apply(this, [$('datatable'), 'data.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
</script>
</head>
<body>
<a title="Export" href="#" id="export">Export to Excel</a>
<div id="datatable">
<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>
</table>
</div>
</body>
</html>