Created
May 25, 2016 12:32
-
-
Save georgeOsdDev/e6914a2bb8230d0cbcc6210003f5409f to your computer and use it in GitHub Desktop.
jsでexcel
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
import encoding from 'encoding-japanese'; | |
import json2csv from 'json2csv'; | |
let json = [{"text": "日本語"}, {"text": "改行\n改行"}] | |
function saveCsvAsFile(text, filename) { | |
const UTF16BOM = '\ufffe'; | |
const isWindows = navigator.platform.indexOf("Win") !== -1; | |
function isLittleEndian(){ | |
if ((new Uint8Array((new Uint16Array([0x00ff])).buffer))[0]) return true; | |
return false; | |
} | |
let contents, file; | |
if (isWindows) { | |
let array = []; | |
for (let i = 0; i < text.length; i++){ | |
array.push(text.charCodeAt(i)); | |
} | |
contents = new Uint8Array(encoding.convert(array, 'SJIS', 'UNICODE')); | |
file = new Blob([contents], {type: 'text/csv;charset=shift_jis;'}); | |
} else { | |
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 | |
} | |
file = new Blob([contents], {type: 'text/csv;charset=utf-16LE;'}); | |
} | |
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); | |
} | |
json2csv({data:json, fields: ["text"], del: '\t'}, (err, csv) => { | |
if (err){ | |
// alert(err); | |
} else { | |
saveCsvAsFile(csv, "my.csv"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment