|
| 1 | +// This file was generated by Mendix Studio Pro. |
| 2 | +// |
| 3 | +// WARNING: Only the following code will be retained when actions are regenerated: |
| 4 | +// - the import list |
| 5 | +// - the code between BEGIN USER CODE and END USER CODE |
| 6 | +// - the code between BEGIN EXTRA CODE and END EXTRA CODE |
| 7 | +// Other code you write will be lost the next time you deploy the project. |
| 8 | +import "mx-global"; |
| 9 | +import { Big } from "big.js"; |
| 10 | +import { utils, writeFileXLSX } from './xlsx-export-tools.js'; |
| 11 | + |
| 12 | +// BEGIN EXTRA CODE |
| 13 | +// END EXTRA CODE |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {string} datagridName |
| 17 | + * @param {string} fileName |
| 18 | + * @param {string} sheetName |
| 19 | + * @param {boolean} includeColumnHeaders |
| 20 | + * @param {Big} chunkSize - The number of items fetched and exported per request. |
| 21 | + * @returns {Promise.<boolean>} |
| 22 | + */ |
| 23 | +export async function Export_To_Excel(datagridName, fileName, sheetName, includeColumnHeaders, chunkSize) { |
| 24 | + // BEGIN USER CODE |
| 25 | + if (!fileName || !datagridName || !sheetName) { |
| 26 | + return false; |
| 27 | + } |
| 28 | + |
| 29 | + const REGISTRY_NAME = "com.mendix.widgets.web.datagrid.export"; |
| 30 | + const registry = window[REGISTRY_NAME]; |
| 31 | + const controller = registry.get(datagridName); |
| 32 | + |
| 33 | + if (controller === undefined) { |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + return new Promise((resolve) => { |
| 38 | + function handler(req) { |
| 39 | + let worksheet; |
| 40 | + let headers; |
| 41 | + |
| 42 | + req.on("headers", (hds) => { |
| 43 | + headers = hds.map(header => header.name); |
| 44 | + if (includeColumnHeaders) { |
| 45 | + worksheet = utils.aoa_to_sheet([headers]); |
| 46 | + } |
| 47 | + }); |
| 48 | + |
| 49 | + req.on("data", (data) => { |
| 50 | + if (worksheet === undefined) { |
| 51 | + worksheet = utils.aoa_to_sheet(data) |
| 52 | + } else { |
| 53 | + utils.sheet_add_aoa(worksheet, data, { origin: -1 }); |
| 54 | + } |
| 55 | + }); |
| 56 | + |
| 57 | + req.on("end", () => { |
| 58 | + if (worksheet) { |
| 59 | + // Set character width for each column |
| 60 | + // https://docs.sheetjs.com/docs/csf/sheet#worksheet-object |
| 61 | + worksheet["!cols"] = headers.map(header => ({ |
| 62 | + wch: header.length + 10 |
| 63 | + })); |
| 64 | + const workbook = utils.book_new(); |
| 65 | + utils.book_append_sheet(workbook, worksheet, sheetName === "" ? "Data" : sheetName); |
| 66 | + writeFileXLSX(workbook, `${fileName}.xlsx`); |
| 67 | + resolve(true); |
| 68 | + } else { |
| 69 | + resolve(false); |
| 70 | + } |
| 71 | + }); |
| 72 | + |
| 73 | + req.on("abort", () => resolve(false)); |
| 74 | + } |
| 75 | + |
| 76 | + controller.exportData(handler, { |
| 77 | + withHeaders: true, |
| 78 | + limit: chunkSize.toNumber() |
| 79 | + }) |
| 80 | + }); |
| 81 | + // END USER CODE |
| 82 | +} |
0 commit comments