Skip to content

Instantly share code, notes, and snippets.

@maciejjankowski
Last active December 30, 2021 18:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maciejjankowski/2db91642fb9eaa771111f2c0538e4560 to your computer and use it in GitHub Desktop.
Save maciejjankowski/2db91642fb9eaa771111f2c0538e4560 to your computer and use it in GitHub Desktop.
download table to excel csv.js. Charset MUST be UTF-16LE - this is the only solution that worked with Excel on Mac
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td,th)'),
// 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 = '"\t"',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td,th');
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) + '"';
// Data URI
var bom = decodeURIComponent("%EF%BB%BF");// "\uFEFF\n";
var byteArray = [];
csv = bom + csv;
csvA = new Uint16Array(csv.split('').map( function(k, v){
return k.charCodeAt(0);
}));
var blob = new Blob([csvA],{type:'text/csv;charset=UTF-16LE;'});
var blobUrl=URL.createObjectURL(blob);
return blobUrl;
}
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', text);
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
download('raport.csv', exportTableToCSV($('#report-data'), 'raport.tsv'));
//saveAs(exportTableToCSV($('#report-data'), "csv.csv"));
// https://raw.githubusercontent.com/dcodeIO/utfx/master/dist/utfx-embeddable.js
// https://github.com/inexorabletash/text-encoding/blob/master/lib/encoding.js
// https://github.com/dcodeIO/utfx/wiki
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment