UNPKG

@nitra/export-excel

Version:
128 lines (114 loc) 3.26 kB
import ExcelJS from 'exceljs' /** * Экспорта таблицы в XLSX * * @param {Object} columns * @param {Object} rows * @param {String} filename * * @return {Promise<*>} */ // exportToExcel export const exportToExcel = async ( columns, rows, type = 'buffer', // workbook or buffer filename = 'export', creator = 'exportToExcel' ) => { // Создаем книгу const workbook = new ExcelJS.Workbook() workbook.creator = creator workbook.created = new Date() // Создаем лист в книге const worksheet = workbook.addWorksheet(filename, { pageSetup: { scale: 90 } }) // добавляем колонки addColumnsToWorksheet(worksheet, columns) // добавляем данные addRowsToWorksheet(worksheet, rows) // добавляем нижнюю границу у таблицы worksheet.lastRow.eachCell({ includeEmpty: true }, function (cell, colNumber) { cell.style.border = { right: { style: 'thin' }, bottom: { style: 'thin' } } }) // добавляем правую границу у колонок const numRows = rows.length worksheet.eachRow(function (row, rowNumber) { if (rowNumber <= numRows) { row.eachCell({ includeEmpty: true }, function (cell) { cell.style.border = { right: { style: 'thin' } } }) } }) if (type === 'workbook') { return workbook } if (type === 'buffer') { return await workbook.xlsx.writeBuffer() } } function addColumnsToWorksheet(worksheet, data) { const columns = [] for (const c of data) { columns.push({ header: c.label, key: c.field, width: c.width || 30, style: { numFmt: c.excelType || '', // маска для форматирования чисел alignment: { horizontal: c.align, vertical: 'middle', wrapText: c.wrapText } } }) } worksheet.columns = columns // форматирование колонок const firstRow = worksheet.getRow(1) firstRow.eachCell((cell, colNumber) => { cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true } cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'ffdddddd' } } cell.font = { size: 12, bold: true } cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } } }) } function addRowsToWorksheet(worksheet, rows) { const columns = worksheet.columns for (const row of rows) { const rowData = {} // берем ключ данных из столбца for (const column of columns) { let value = row[column._key] // если в колонке есть форматирование для чисел то данные преобразовываем в число if (column.style && column.style.numFmt && column.style.numFmt.search('#') !== -1) { value = parseFloat(value || 0) } else { // иначе в строку value = value ? value.toString() : '' } rowData[column._key] = value } worksheet.addRow(rowData) } }