Last active
December 30, 2021 18:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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