1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import XLSX from 'xlsx'
function autoWidthFunc(ws, data) { const colWidth = data.map(row => row.map(val => { if (val == null) { return { wch: 10 } } else if (val.toString().charCodeAt(0) > 255) { return { wch: val.toString().length * 2 } } return { wch: val.toString().length } })) const result = colWidth[0] for (let i = 1; i < colWidth.length; i++) { for (let j = 0; j < colWidth[i].length; j++) { if (result[j].wch < colWidth[i][j].wch) { result[j].wch = colWidth[i][j].wch } } } ws['!cols'] = result }
function jsonToArray(key, jsonData) { return jsonData.map(v => key.map(j => { return v[j] })) }
export function exportArrayToExcel({ key, data, title, fileName, autoWidth, columnsWidth }) { const wb = XLSX.utils.book_new() const arr = jsonToArray(key, data) arr.unshift(title) const ws = XLSX.utils.aoa_to_sheet(arr) if (autoWidth) { autoWidthFunc(ws, arr) } else if (columnsWidth) { ws['!cols'] = columnsWidth } XLSX.utils.book_append_sheet(wb, ws, fileName) XLSX.writeFile(wb, `${fileName}.xlsx`) }
|