UNPKG

table-xlsx

Version:

Based on SheetJS encapsulation, the function of exporting files and parsing files to generate table data is realized

707 lines (670 loc) 26.1 kB
/******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./src/exportFile.ts": /*!***************************!*\ !*** ./src/exportFile.ts ***! \***************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getWorkbook = exports.exportFile = void 0; var base_1 = __webpack_require__(/*! ./utils/base */ "./src/utils/base.ts"); var columnsUtils_1 = __webpack_require__(/*! ./utils/columnsUtils */ "./src/utils/columnsUtils.ts"); var valueUtils_1 = __webpack_require__(/*! ./utils/valueUtils */ "./src/utils/valueUtils.ts"); var cellStylesUtils_1 = __webpack_require__(/*! ./utils/cellStylesUtils */ "./src/utils/cellStylesUtils.ts"); var XLSX = __webpack_require__(/*! @pengchen/xlsx */ "@pengchen/xlsx"); /** * 导出 * @param fileName * @param sheetNames * @param columns * @param dataSource * @param showHeader 是否显示表头 * @param raw 是否格式化值的类型 * @param cellStyle 单元格样式 * @param headerCellStyle 单元格样式 * @param bodyCellStyle 单元格样式 * @param useRender 是否使用render返回的值 * @param rowHpx * @param onTxBodyRow */ var exportFile = function (_a) { var _b = _a.fileName, fileName = _b === void 0 ? 'table.xlsx' : _b, _c = _a.sheetNames, sheetNames = _c === void 0 ? ['sheet1'] : _c, _d = _a.columns, columns = _d === void 0 ? [] : _d, _e = _a.dataSource, dataSource = _e === void 0 ? [] : _e, _f = _a.showHeader, showHeader = _f === void 0 ? true : _f, _g = _a.raw, raw = _g === void 0 ? false : _g, _h = _a.rowHpx, rowHpx = _h === void 0 ? 25 : _h, _j = _a.cellStyle, cellStyle = _j === void 0 ? {} : _j, _k = _a.headerCellStyle, headerCellStyle = _k === void 0 ? {} : _k, _l = _a.bodyCellStyle, bodyCellStyle = _l === void 0 ? {} : _l, _m = _a.useRender, useRender = _m === void 0 ? true : _m, onTxBodyRow = _a.onTxBodyRow; var wb = (0, exports.getWorkbook)({ sheetNames: sheetNames, columns: columns, dataSource: dataSource, showHeader: showHeader, raw: raw, rowHpx: rowHpx, cellStyle: cellStyle, headerCellStyle: headerCellStyle, bodyCellStyle: bodyCellStyle, useRender: useRender, onTxBodyRow: onTxBodyRow, }); XLSX.writeFile(wb, fileName); return wb; }; exports.exportFile = exportFile; /** * 获取wb对象 */ var getWorkbook = function (_a) { var _b = _a.sheetNames, sheetNames = _b === void 0 ? ['sheet1'] : _b, _c = _a.columns, columns = _c === void 0 ? [] : _c, _d = _a.dataSource, dataSource = _d === void 0 ? [] : _d, _e = _a.showHeader, showHeader = _e === void 0 ? true : _e, _f = _a.raw, raw = _f === void 0 ? false : _f, _g = _a.rowHpx, rowHpx = _g === void 0 ? 25 : _g, _h = _a.cellStyle, cellStyle = _h === void 0 ? {} : _h, _j = _a.headerCellStyle, headerCellStyle = _j === void 0 ? {} : _j, _k = _a.bodyCellStyle, bodyCellStyle = _k === void 0 ? {} : _k, _l = _a.useRender, useRender = _l === void 0 ? true : _l, onTxBodyRow = _a.onTxBodyRow; var Sheets = {}; sheetNames.forEach(function (sheetName, sheetIndex) { var _columns = (0, base_1.sameType)(columns[sheetIndex], 'Array') ? columns[sheetIndex] : columns; var _dataSource = (0, base_1.sameType)(dataSource[sheetIndex], 'Array') ? dataSource[sheetIndex] : dataSource; var sheet = formatToSheet({ columns: _columns, dataSource: _dataSource, useRender: useRender, showHeader: showHeader, raw: raw, rowHpx: rowHpx, cellStyle: cellStyle, headerCellStyle: headerCellStyle, bodyCellStyle: bodyCellStyle, onTxBodyRow: onTxBodyRow, }).sheet; Sheets[sheetName] = sheet; }); return { SheetNames: sheetNames, Sheets: Sheets, }; }; exports.getWorkbook = getWorkbook; /** * 转换成sheet对象 */ var formatToSheet = function (_a) { var columns = _a.columns, dataSource = _a.dataSource, showHeader = _a.showHeader, raw = _a.raw, rowHpx = _a.rowHpx, cellStyle = _a.cellStyle, headerCellStyle = _a.headerCellStyle, bodyCellStyle = _a.bodyCellStyle, useRender = _a.useRender, onTxBodyRow = _a.onTxBodyRow; var sheet = {}; var $cols = []; var $rows = []; var $merges = []; // var _b = (0, columnsUtils_1.flattenColumns)({ columns: columns }), flatColumns = _b.columns, level = _b.level; var headerLevel = level; if (showHeader) { for (var i = 0; i < headerLevel; i++) { $rows.push({ hpx: rowHpx }); } // 表头信息 var headerData = getHeaderData({ columns: columns, headerLevel: headerLevel, cellStyle: cellStyle, headerCellStyle: headerCellStyle }); Object.assign(sheet, headerData.sheet); $merges.push.apply($merges, headerData.merges); } else { headerLevel = 0; } // flatColumns.forEach(function (col, colIndex) { var key = col.dataIndex || col.key; $cols.push({ wpx: (0, columnsUtils_1.formatToWpx)(col.width || col.minWidth) }); var xAxis = XLSX.utils.encode_col(colIndex); dataSource.forEach(function (data, rowIndex) { if (colIndex === 0) { $rows.push({ hpx: rowHpx }); } var value = (0, valueUtils_1.getPathValue)(data, key); if (col.render) { var renderResult = col.render(value, data, rowIndex); value = useRender ? (0, valueUtils_1.getRenderValue)(renderResult) : value; var merge = getMerge({ renderResult: renderResult, colIndex: colIndex, rowIndex: rowIndex, headerLevel: headerLevel }); if (merge) { $merges.push(merge); } } if (col.xlsxRender) { value = col.xlsxRender(value, data, rowIndex); } var txBodyRowStyle = {}; var txBodyCellStyle = {}; if (onTxBodyRow) { var result = onTxBodyRow(data, rowIndex); txBodyRowStyle = (result === null || result === void 0 ? void 0 : result.style) || {}; } if (col.onTxBodyCell) { var result = col.onTxBodyCell(data, rowIndex); txBodyCellStyle = (result === null || result === void 0 ? void 0 : result.style) || {}; } sheet["".concat(xAxis).concat(headerLevel + rowIndex + 1)] = { t: ((raw && typeof value === 'number') || col.valueType === 'number') ? 'n' : 's', v: value !== null && value !== void 0 ? value : '', s: (0, cellStylesUtils_1.getStyles)(__assign(__assign(__assign(__assign({ alignmentHorizontal: 'left' }, cellStyle), bodyCellStyle), txBodyRowStyle), txBodyCellStyle)), }; }); }); var xe = XLSX.utils.encode_col(Math.max(flatColumns.length - 1, 0)); var ye = headerLevel + dataSource.length; sheet['!ref'] = "A1:".concat(xe).concat(ye); sheet['!cols'] = $cols; sheet['!rows'] = $rows; sheet['!merges'] = $merges; return { sheet: sheet }; }; /** * 获取表头数据 */ var getHeaderData = function (_a) { var columns = _a.columns, headerLevel = _a.headerLevel, cellStyle = _a.cellStyle, headerCellStyle = _a.headerCellStyle; var sheet = {}; var merges = []; var headerArr = (0, columnsUtils_1.getHeader2dArray)({ columns: columns, headerLevel: headerLevel }); var mergesWeakMap = new WeakMap(); headerArr.forEach(function (rowsArr, rowIndex) { rowsArr.forEach(function (cols, colIndex) { var xAxis = XLSX.utils.encode_col(colIndex); var style = (cols === null || cols === void 0 ? void 0 : cols.txHeaderCellStyle) || {}; // https://github.com/SheetJS/sheetjs#cell-object sheet["".concat(xAxis).concat(rowIndex + 1)] = { t: 's', v: cols.title, s: (0, cellStylesUtils_1.getStyles)(__assign(__assign(__assign({ fillFgColorRgb: 'e9ebf0', fontBold: true }, cellStyle), headerCellStyle), style)), }; if (cols.merges && !mergesWeakMap.get(cols.merges)) { mergesWeakMap.set(cols.merges, true); // Microsoft Excel 如果传了相同的merges信息,文件会损坏,做个去重 merges.push(cols.merges); } }); }); return { sheet: sheet, merges: merges }; }; /** * 获取单个合并信息 */ var getMerge = function (_a) { var renderResult = _a.renderResult, colIndex = _a.colIndex, rowIndex = _a.rowIndex, headerLevel = _a.headerLevel; if (renderResult === null || renderResult === void 0 ? void 0 : renderResult.props) { var _b = renderResult.props, colSpan = _b.colSpan, rowSpan = _b.rowSpan; if ((colSpan && colSpan !== 1) || (rowSpan && rowSpan !== 1)) { var realRowIndex = rowIndex + headerLevel; var merge = { s: { c: colIndex, r: realRowIndex }, e: { c: colIndex + (colSpan || 1) - 1, r: realRowIndex + (rowSpan || 1) - 1 }, }; return merge; } } return false; }; /***/ }), /***/ "./src/parseFile.ts": /*!**************************!*\ !*** ./src/parseFile.ts ***! \**************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getMergesObj = exports.getColumns = exports.parseFile = void 0; var XLSX = __webpack_require__(/*! @pengchen/xlsx */ "@pengchen/xlsx"); /** * 读取文件 */ var parseFile = function (_a) { var file = _a.file; return new Promise(function (resolve, reject) { var reader = new FileReader(); var rABS = !!reader.readAsBinaryString; reader.onload = function (e) { /* Parse data */ var bstr = e.target && e.target.result; var wb = XLSX.read(bstr, { type: rABS ? 'binary' : 'array', cellStyles: true }); /* Get Tables */ var tables = []; wb.SheetNames.forEach(function (sheetName) { var ws = wb.Sheets[sheetName]; // https://github.com/SheetJS/sheetjs#json var dataSource = XLSX.utils.sheet_to_json(ws, { header: 'A', blankrows: true }); var columns = (0, exports.getColumns)({ refStr: ws['!ref'], mergesArr: ws['!merges'] || [], }); tables.push({ sheetName: sheetName, dataSource: dataSource, columns: columns, }); }); resolve({ wb: wb, tables: tables, }); }; reader.onerror = function (e) { reject(e); }; if (rABS) reader.readAsBinaryString(file); else reader.readAsArrayBuffer(file); }); }; exports.parseFile = parseFile; /** * 生成列 */ var getColumns = function (_a) { var refStr = _a.refStr, mergesArr = _a.mergesArr; var columns = []; if (!refStr) { return columns; } var mergesObj = (0, exports.getMergesObj)(mergesArr); var columnsLen = XLSX.utils.decode_range(refStr).e.c + 1; var _loop_1 = function (colIndex) { columns[colIndex] = { key: XLSX.utils.encode_col(colIndex), title: XLSX.utils.encode_col(colIndex), dataIndex: XLSX.utils.encode_col(colIndex), mergesObj: mergesObj, render: function (value, row, rowIndex) { return { children: value, props: mergesObj["".concat(colIndex, ":").concat(rowIndex)], }; }, }; }; for (var colIndex = 0; colIndex < columnsLen; ++colIndex) { _loop_1(colIndex); } return columns; }; exports.getColumns = getColumns; /** * 获取合并项 */ var getMergesObj = function (mergesArr) { var mergesObj = {}; mergesArr.forEach(function (m) { var msc = m.s.c; var msr = m.s.r; var mec = m.e.c; var mer = m.e.r; for (var sc = msc; sc <= mec; sc++) { for (var sr = msr; sr <= mer; sr++) { mergesObj["".concat(sc, ":").concat(sr)] = { colSpan: msr === sr ? 0 : undefined, rowSpan: 0, }; } } mergesObj["".concat(msc, ":").concat(msr)] = { colSpan: mec - msc + 1, rowSpan: mer - msr + 1, }; }); return mergesObj; }; exports.getMergesObj = getMergesObj; /***/ }), /***/ "./src/utils/base.ts": /*!***************************!*\ !*** ./src/utils/base.ts ***! \***************************/ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sameType = void 0; /** * 判断类型 * @param {any} value 需要比对的值 * @param {string} type 比对类型 * @return {boolean} 比对结果 */ var sameType = function (value, type) { if (type === 'String') { return Object.prototype.toString.call(value) === '[object String]'; } if (type === 'Number') { return Object.prototype.toString.call(value) === '[object Number]'; } if (type === 'Symbol') { return Object.prototype.toString.call(value) === '[object Symbol]'; } if (type === 'Null') { return Object.prototype.toString.call(value) === '[object Null]'; } if (type === 'Undefined') { return Object.prototype.toString.call(value) === '[object Undefined]'; } if (type === 'Function') { return Object.prototype.toString.call(value) === '[object Function]'; } if (type === 'Object') { return Object.prototype.toString.call(value) === '[object Object]'; } if (type === 'Array') { return Object.prototype.toString.call(value) === '[object Array]'; } if (type === 'Boolean') { return Object.prototype.toString.call(value) === '[object Boolean]'; } }; exports.sameType = sameType; /***/ }), /***/ "./src/utils/cellStylesUtils.ts": /*!**************************************!*\ !*** ./src/utils/cellStylesUtils.ts ***! \**************************************/ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getStyles = void 0; var getStyles = function (_a) { var _b = _a.fontName, fontName = _b === void 0 ? 'Calibri' : _b, _c = _a.fontColorRgb, fontColorRgb = _c === void 0 ? '333333' : _c, _d = _a.fontBold, fontBold = _d === void 0 ? false : _d, _e = _a.fillFgColorRgb, fillFgColorRgb = _e === void 0 ? 'ffffff' : _e, _f = _a.borderStyle, borderStyle = _f === void 0 ? 'thin' : _f, _g = _a.borderColorRgb, borderColorRgb = _g === void 0 ? 'd1d3d8' : _g, _h = _a.alignmentHorizontal, alignmentHorizontal = _h === void 0 ? 'center' : _h, // left center right _j = _a.alignmentVertical, // left center right alignmentVertical = _j === void 0 ? 'center' : _j, // top center bottom _k = _a.alignmentWrapText, // top center bottom alignmentWrapText = _k === void 0 ? false : _k, // true false _l = _a.alignmentReadingOrder, // true false alignmentReadingOrder = _l === void 0 ? 2 : _l, // for right-to-left _m = _a.alignmentTextRotation, // for right-to-left alignmentTextRotation = _m === void 0 ? 0 : _m; return { fill: { fgColor: { rgb: formatRgb(fillFgColorRgb) } }, font: { name: fontName, color: { rgb: formatRgb(fontColorRgb) }, bold: fontBold, }, border: getDefaultBorder({ style: borderStyle, colorRgb: formatRgb(borderColorRgb) }), numFmt: undefined, alignment: { horizontal: alignmentHorizontal, vertical: alignmentVertical, wrapText: alignmentWrapText, readingOrder: alignmentReadingOrder, textRotation: alignmentTextRotation, }, }; }; exports.getStyles = getStyles; var getDefaultBorder = function (_a) { var _b = _a.style, style = _b === void 0 ? 'thin' : _b, _c = _a.colorRgb, colorRgb = _c === void 0 ? 'd1d3d8' : _c; var border = { top: { style: style, color: { rgb: colorRgb, // ARGB // auto: 1, // theme: '1', // tint: '-0.25', // index: 64 } }, left: { style: style, color: { rgb: colorRgb } }, bottom: { style: style, color: { rgb: colorRgb } }, right: { style: style, color: { rgb: colorRgb } }, diagonal: { style: style, color: { rgb: colorRgb } } }; return border; }; var formatRgb = function (hex) { return hex.replace('#', ''); }; /***/ }), /***/ "./src/utils/columnsUtils.ts": /*!***********************************!*\ !*** ./src/utils/columnsUtils.ts ***! \***********************************/ /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.formatToWpx = exports.getHeader2dArray = exports.flattenColumns = void 0; /** * 扁平化列 */ var flattenColumns = function (_a) { var columns = _a.columns, _b = _a.childrenField, childrenField = _b === void 0 ? 'children' : _b; var newColumns = []; var level = []; var flatten = function (_columns, index) { if (index === void 0) { index = 0; } level[index] = true; index += 1; _columns.forEach(function (column) { var childColumns = column[childrenField]; if (childColumns && childColumns.length > 0) { flatten(childColumns, index); } else { newColumns.push(column); } }); }; flatten(columns); return { level: level.length, columns: newColumns }; }; exports.flattenColumns = flattenColumns; /** * 获取表头二维数组 */ var getHeader2dArray = function (_a) { var columns = _a.columns, headerLevel = _a.headerLevel, _b = _a.childrenField, childrenField = _b === void 0 ? 'children' : _b; var arr = []; var deal = function (_columns, startCol, rowLevel) { if (startCol === void 0) { startCol = 0; } if (rowLevel === void 0) { rowLevel = 0; } _columns.reduce(function (prevCol, currentColumn) { if (!arr[rowLevel]) { arr[rowLevel] = []; } arr[rowLevel][prevCol] = currentColumn; var nextCol = prevCol; var childColumns = currentColumn[childrenField]; if (childColumns) { deal(childColumns, prevCol, rowLevel + 1); var flatChildColumns = (0, exports.flattenColumns)({ columns: childColumns, childrenField: childrenField }).columns; nextCol += flatChildColumns.length; arr[rowLevel][prevCol].merges = { s: { c: prevCol, r: rowLevel }, e: { c: nextCol - 1, r: rowLevel }, }; // 补全值 跨行的值 for (var c = prevCol + 1; c < nextCol; c++) { arr[rowLevel][c] = currentColumn; } } else { nextCol += 1; // 有跨列 if (headerLevel - 1 - rowLevel > 0) { arr[rowLevel][prevCol].merges = { s: { c: prevCol, r: rowLevel }, e: { c: prevCol, r: headerLevel - 1 }, }; // 补全值 跨列的值 for (var r = rowLevel + 1; r < headerLevel; r++) { if (!arr[r]) { arr[r] = []; } arr[r][prevCol] = currentColumn; } } } return nextCol; }, startCol); }; deal(columns); return arr; }; exports.getHeader2dArray = getHeader2dArray; /** * 获取列宽 */ var formatToWpx = function (width) { var wpx = width || 100; if (typeof wpx === 'string') { wpx = Number(wpx.replace(/[^0-9]/ig, '')); } return wpx; }; exports.formatToWpx = formatToWpx; /***/ }), /***/ "./src/utils/valueUtils.ts": /*!*********************************!*\ !*** ./src/utils/valueUtils.ts ***! \*********************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRenderValue = exports.getPathValue = void 0; var base_1 = __webpack_require__(/*! ./base */ "./src/utils/base.ts"); function toArray(arr) { if (arr === undefined || arr === null) { return []; } return (Array.isArray(arr) ? arr : [arr]); } /** * 通过path获取值 */ var getPathValue = function (record, path) { // Skip if path is empty if (!path && typeof path !== 'number') { return ''; } var pathList = toArray(path); var current = record; for (var i = 0; i < pathList.length; i += 1) { if (!current) { return ''; } var prop = pathList[i]; current = current[prop]; } return current; }; exports.getPathValue = getPathValue; /** * 获取render值 */ var getRenderValue = function (renderResult) { var values = []; var dealChildren = function (child) { if ((0, base_1.sameType)(child, 'String') || (0, base_1.sameType)(child, 'Number')) { values.push(child); } if ((0, base_1.sameType)(child, 'Object')) { var children = child.props.children; if ((0, base_1.sameType)(children, 'String') || (0, base_1.sameType)(children, 'Number')) { values.push(children); } if ((0, base_1.sameType)(children, 'Object')) { dealChildren(children); } if ((0, base_1.sameType)(children, 'Array')) { children.forEach(function (_child) { dealChildren(_child); }); } } if ((0, base_1.sameType)(child, 'Array')) { child.forEach(function (_child) { dealChildren(_child); }); } }; // 解决数据为{ children: 0 }时会变为''的问题 if ((renderResult === null || renderResult === void 0 ? void 0 : renderResult.children) || (renderResult === null || renderResult === void 0 ? void 0 : renderResult.children) === 0) { dealChildren(renderResult.children); } else { dealChildren(renderResult); } return values.join(''); }; exports.getRenderValue = getRenderValue; /***/ }), /***/ "@pengchen/xlsx": /*!*********************************!*\ !*** external "@pengchen/xlsx" ***! \*********************************/ /***/ ((module) => { module.exports = require("@pengchen/xlsx"); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { var exports = __webpack_exports__; /*!**********************!*\ !*** ./src/index.ts ***! \**********************/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getWorkbook = exports.exportFile = exports.parseFile = void 0; var parseFile_1 = __webpack_require__(/*! ./parseFile */ "./src/parseFile.ts"); Object.defineProperty(exports, "parseFile", ({ enumerable: true, get: function () { return parseFile_1.parseFile; } })); var exportFile_1 = __webpack_require__(/*! ./exportFile */ "./src/exportFile.ts"); Object.defineProperty(exports, "exportFile", ({ enumerable: true, get: function () { return exportFile_1.exportFile; } })); Object.defineProperty(exports, "getWorkbook", ({ enumerable: true, get: function () { return exportFile_1.getWorkbook; } })); })(); module.exports = __webpack_exports__; /******/ })() ; //# sourceMappingURL=table-xlsx.development.js.map