|
1 | 1 | // add XML export to file |
2 | 2 | import "https://unpkg.com/write-excel-file@1.x/bundle/write-excel-file.min.js"; |
3 | 3 |
|
| 4 | +const regexISO = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/; |
| 5 | + |
4 | 6 | export async function exportXLSFile(headers, lines, fileTitle) { |
5 | 7 | try { |
6 | 8 | console.log({ headers, lines }); |
7 | 9 |
|
8 | | - const schema = Object.entries(headers).map((h) => { |
9 | | - const key = h[0]; |
10 | | - return { |
11 | | - column: h[1], |
12 | | - value: function (e) { |
13 | | - return e[key]; |
14 | | - }, |
15 | | - }; |
16 | | - }); |
| 10 | + const headersXLS = Object.values(headers).map((h) => ({ |
| 11 | + value: h, |
| 12 | + fontWeight: 'bold', |
| 13 | + })); |
| 14 | + const columns = headersXLS.map((e) => ({ width: e.value.length + 2 })); |
| 15 | + |
| 16 | + const dataXLS = []; |
| 17 | + dataXLS.push(headersXLS); |
| 18 | + for (const line of lines) { |
| 19 | + const row = []; |
| 20 | + dataXLS.push(row); |
| 21 | + let i = 0; |
| 22 | + for (const [key, label] of Object.entries(headers)) { |
| 23 | + const cell = { value: line[key] }; |
| 24 | + let myLength = 10; |
| 25 | + |
| 26 | + // -- number |
| 27 | + const n = Number(cell.value); |
| 28 | + if (!Number.isNaN(n)) { |
| 29 | + cell.value = n; |
| 30 | + cell.type = Number; |
| 31 | + } else if (typeof cell.value === 'string') { // date |
| 32 | + myLength = cell.value.length; |
| 33 | + const fulldate = cell.value.endsWith('Z'); |
| 34 | + const t = fulldate ? cell.value : cell.value + 'T00:00:00.000Z'; |
17 | 35 |
|
| 36 | + if (regexISO.test(t)) { |
| 37 | + cell.value = new Date(t); |
| 38 | + cell.type = Date; |
| 39 | + cell.format = fulldate ? 'yyyy-mm-dd hh:mm:ss' : 'yyyy-mm-dd' |
| 40 | + myLength = fulldate ? 18 : 11; |
| 41 | + } |
18 | 42 |
|
19 | | - const exportedFilename = fileTitle + ".xlsx" || "export.xlsx"; |
20 | | - await writeXlsxFile(lines, { |
21 | | - schema, |
| 43 | + } |
| 44 | + row.push(cell); |
| 45 | + myLength = Math.min(myLength, 33) + 2; |
| 46 | + if (columns[i].width < myLength) columns[i].width = myLength; |
| 47 | + i++; |
| 48 | + } |
| 49 | + } |
| 50 | + console.log('## columns', {columns}); |
| 51 | + const exportedFilename = fileTitle + '.xlsx' || 'export.xlsx'; |
| 52 | + await writeXlsxFile(dataXLS, { |
| 53 | + columns, |
22 | 54 | fileName: exportedFilename, |
23 | 55 | }); |
24 | 56 | } catch (e) { |
|
0 commit comments