Skip to content

Instantly share code, notes, and snippets.

@lucasdu4rte
Created April 29, 2019 11:49
Show Gist options
  • Save lucasdu4rte/50d79691c0c907967124f38a46e2d91c to your computer and use it in GitHub Desktop.
Save lucasdu4rte/50d79691c0c907967124f38a46e2d91c to your computer and use it in GitHub Desktop.
Gerar Arquivo Excel com JSON usando a lib XLSX no Javascript
// É necessário instalar o xlsx
// Foi testado com a versão "xlsx": "^0.14.2"
function Workbook() {
if (!(this instanceof Workbook))
return new Workbook()
this.SheetNames = []
this.Sheets = {}
}
const download = (url, name) => {
let a = document.createElement('a')
a.href = url
a.download = name
a.click()
window.URL.revokeObjectURL(url)
}
function s2ab(s) {
const buf = new ArrayBuffer(s.length)
const view = new Uint8Array(buf)
for (let i=0; i !== s.length; ++i)
view[i] = s.charCodeAt(i) & 0xFF
return buf
}
export default (data, filename) => {
import('xlsx').then(XLSX => {
const wb = new Workbook()
const ws = XLSX.utils.json_to_sheet(data)
wb.SheetNames.push('')
wb.Sheets[''] = ws
const wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'binary'})
let url = window.URL.createObjectURL(new Blob([s2ab(wbout)], {type:'application/octet-stream'}))
download(url, filename || 'relatorio.xlsx')
})
}
// Para usar execute:
// exportToExcel({ nome: 'Teste', email: 'teste@email.com' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment