Skip to content

Instantly share code, notes, and snippets.

@yayoc
Created July 22, 2014 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yayoc/03c10a17d02f3471f68c to your computer and use it in GitHub Desktop.
Save yayoc/03c10a17d02f3471f68c to your computer and use it in GitHub Desktop.
Export CSV
$(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('"', '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=Shift-JIS,' + EscapeSJIS(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// This must be a hyperlink
$(".export").on('click', function (event) {
var self = $(this);
var UA = window.navigator.userAgent.toLowerCase();
if (UA.indexOf('msie') != -1) {
window.location = self.attr("href");
}
// CSV
exportTableToCSV.apply(this, [$('#List>table'), 'export.csv']);
});
});
@yayoc
Copy link
Author

yayoc commented Jul 22, 2014

EscapeSJIS function is defined in enc.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment