Skip to content

Instantly share code, notes, and snippets.

@georgeOsdDev
Created August 14, 2017 03:25
Show Gist options
  • Save georgeOsdDev/41a98af8b3df4cd26836cf4019447646 to your computer and use it in GitHub Desktop.
Save georgeOsdDev/41a98af8b3df4cd26836cf4019447646 to your computer and use it in GitHub Desktop.
Save excel friendly csv for Mac/Windows
// Save excel friendly csv for Mac/Windows.
// See also
// http://qiita.com/bump_of_kiharu/items/f41beec668e1f3ea675e#%E5%8F%82%E8%80%83
// https://stackoverflow.com/questions/17879198/adding-utf-8-bom-to-string-blob
const UTF16BOM = '\ufeff';
const isIE = false || !!document.documentMode;
const isEdge = navigator && /Edge\/\d./i.test(navigator.userAgent);
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness
const isLittleEndian = (() => {
let buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
return new Int16Array(buffer)[0] === 256;
})();
function saveCsvAsFile(text, filename) {
let contents;
const csvString = UTF16BOM + text; //UTF-16
if (isLittleEndian()) {
let array = [];
for (let i = 0; i < csvString.length; i++){
array.push(csvString.charCodeAt(i));
}
contents = new Uint16Array(array);
} else {
let buf = new ArrayBuffer(csvString.length * 2);
let view = new DataView(buf);
for (let i = 0, j = 0; i < csvString.length; i++, j = i * 2) {
view.setUint16( j, csvString.charCodeAt(i), true );
}
contents = buf;
}
const file = new Blob([contents], {type: 'text/csv;charset=utf-16le;'});
if (isIE || isEdge) {
navigator.msSaveBlob(file, filename);
} else {
const url = window.URL.createObjectURL(file);
const body = document.body;
const a = document.createElement('a');
body.appendChild(a);
a.setAttribute('download', filename);
a.setAttribute('href', url);
a.style.display = 'none';
a.click();
a.parentNode.removeChild(a);
setTimeout(function() {
window.URL.revokeObjectURL(url);
}, 10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment