vxe-table-plugin-export-xlsx.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  2. (function (global, factory) {
  3. if (typeof define === "function" && define.amd) {
  4. define("vxe-table-plugin-export-xlsx", ["exports", "xe-utils", "exceljs"], factory);
  5. } else if (typeof exports !== "undefined") {
  6. factory(exports, require("xe-utils"), require("exceljs"));
  7. } else {
  8. var mod = {
  9. exports: {}
  10. };
  11. factory(mod.exports, global.XEUtils, global.ExcelJS);
  12. global.VXETablePluginExportXLSX = mod.exports.default;
  13. }
  14. })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _xeUtils, ExcelJS) {
  15. "use strict";
  16. Object.defineProperty(_exports, "__esModule", {
  17. value: true
  18. });
  19. _exports["default"] = _exports.VXETablePluginExportXLSX = void 0;
  20. _xeUtils = _interopRequireDefault(_xeUtils);
  21. ExcelJS = _interopRequireWildcard(ExcelJS);
  22. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  23. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  24. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  25. var defaultHeaderBackgroundColor = 'f8f8f9';
  26. var defaultCellFontColor = '606266';
  27. var defaultCellBorderStyle = 'thin';
  28. var defaultCellBorderColor = 'e8eaec';
  29. function getCellLabel(column, cellValue) {
  30. if (cellValue) {
  31. switch (column.cellType) {
  32. case 'string':
  33. return _xeUtils["default"].toValueString(cellValue);
  34. case 'number':
  35. if (!isNaN(cellValue)) {
  36. return Number(cellValue);
  37. }
  38. break;
  39. default:
  40. if (cellValue.length < 12 && !isNaN(cellValue)) {
  41. return Number(cellValue);
  42. }
  43. break;
  44. }
  45. }
  46. return cellValue;
  47. }
  48. function getFooterData(opts, footerData) {
  49. var footerFilterMethod = opts.footerFilterMethod;
  50. return footerFilterMethod ? footerData.filter(function (items, index) {
  51. return footerFilterMethod({
  52. items: items,
  53. $rowIndex: index
  54. });
  55. }) : footerData;
  56. }
  57. function getFooterCellValue($table, opts, rows, column) {
  58. var cellValue = getCellLabel(column, rows[$table.getVMColumnIndex(column)]);
  59. return cellValue;
  60. }
  61. function getValidColumn(column) {
  62. var childNodes = column.childNodes;
  63. var isColGroup = childNodes && childNodes.length;
  64. if (isColGroup) {
  65. return getValidColumn(childNodes[0]);
  66. }
  67. return column;
  68. }
  69. function setExcelRowHeight(excelRow, height) {
  70. if (height) {
  71. excelRow.height = _xeUtils["default"].floor(height * 0.75, 12);
  72. }
  73. }
  74. function setExcelCellStyle(excelCell, align) {
  75. excelCell.protection = {
  76. locked: false
  77. };
  78. excelCell.alignment = {
  79. vertical: 'middle',
  80. horizontal: align || 'left'
  81. };
  82. }
  83. function getDefaultBorderStyle() {
  84. return {
  85. top: {
  86. style: defaultCellBorderStyle,
  87. color: {
  88. argb: defaultCellBorderColor
  89. }
  90. },
  91. left: {
  92. style: defaultCellBorderStyle,
  93. color: {
  94. argb: defaultCellBorderColor
  95. }
  96. },
  97. bottom: {
  98. style: defaultCellBorderStyle,
  99. color: {
  100. argb: defaultCellBorderColor
  101. }
  102. },
  103. right: {
  104. style: defaultCellBorderStyle,
  105. color: {
  106. argb: defaultCellBorderColor
  107. }
  108. }
  109. };
  110. }
  111. function exportXLSX(params) {
  112. var msgKey = 'xlsx';
  113. var $table = params.$table,
  114. options = params.options,
  115. columns = params.columns,
  116. colgroups = params.colgroups,
  117. datas = params.datas;
  118. var $vxe = $table.$vxe,
  119. rowHeight = $table.rowHeight,
  120. allHeaderAlign = $table.headerAlign,
  121. allAlign = $table.align,
  122. allFooterAlign = $table.footerAlign;
  123. var modal = $vxe.modal,
  124. t = $vxe.t;
  125. var message = options.message,
  126. sheetName = options.sheetName,
  127. isHeader = options.isHeader,
  128. isFooter = options.isFooter,
  129. isMerge = options.isMerge,
  130. isColgroup = options.isColgroup,
  131. original = options.original,
  132. useStyle = options.useStyle,
  133. sheetMethod = options.sheetMethod;
  134. var showMsg = message !== false;
  135. var mergeCells = $table.getMergeCells();
  136. var colList = [];
  137. var footList = [];
  138. var sheetCols = [];
  139. var sheetMerges = [];
  140. var beforeRowCount = 0;
  141. var colHead = {};
  142. columns.forEach(function (column) {
  143. var id = column.id,
  144. property = column.property,
  145. renderWidth = column.renderWidth;
  146. colHead[id] = original ? property : column.getTitle();
  147. sheetCols.push({
  148. key: id,
  149. width: _xeUtils["default"].ceil(renderWidth / 8, 1)
  150. });
  151. }); // 处理表头
  152. if (isHeader) {
  153. // 处理分组
  154. if (isColgroup && !original && colgroups) {
  155. colgroups.forEach(function (cols, rIndex) {
  156. var groupHead = {};
  157. columns.forEach(function (column) {
  158. groupHead[column.id] = null;
  159. });
  160. cols.forEach(function (column) {
  161. var _colSpan = column._colSpan,
  162. _rowSpan = column._rowSpan;
  163. var validColumn = getValidColumn(column);
  164. var columnIndex = columns.indexOf(validColumn);
  165. groupHead[validColumn.id] = original ? validColumn.property : column.getTitle();
  166. if (_colSpan > 1 || _rowSpan > 1) {
  167. sheetMerges.push({
  168. s: {
  169. r: rIndex,
  170. c: columnIndex
  171. },
  172. e: {
  173. r: rIndex + _rowSpan - 1,
  174. c: columnIndex + _colSpan - 1
  175. }
  176. });
  177. }
  178. });
  179. colList.push(groupHead);
  180. });
  181. } else {
  182. colList.push(colHead);
  183. }
  184. beforeRowCount += colList.length;
  185. } // 处理合并
  186. if (isMerge && !original) {
  187. mergeCells.forEach(function (mergeItem) {
  188. var mergeRowIndex = mergeItem.row,
  189. mergeRowspan = mergeItem.rowspan,
  190. mergeColIndex = mergeItem.col,
  191. mergeColspan = mergeItem.colspan;
  192. sheetMerges.push({
  193. s: {
  194. r: mergeRowIndex + beforeRowCount,
  195. c: mergeColIndex
  196. },
  197. e: {
  198. r: mergeRowIndex + beforeRowCount + mergeRowspan - 1,
  199. c: mergeColIndex + mergeColspan - 1
  200. }
  201. });
  202. });
  203. }
  204. var rowList = datas.map(function (item) {
  205. var rest = {};
  206. columns.forEach(function (column) {
  207. rest[column.id] = getCellLabel(column, item[column.id]);
  208. });
  209. return rest;
  210. });
  211. beforeRowCount += rowList.length; // 处理表尾
  212. if (isFooter) {
  213. var _$table$getTableData = $table.getTableData(),
  214. footerData = _$table$getTableData.footerData;
  215. var footers = getFooterData(options, footerData);
  216. var mergeFooterItems = $table.getMergeFooterItems(); // 处理合并
  217. if (isMerge && !original) {
  218. mergeFooterItems.forEach(function (mergeItem) {
  219. var mergeRowIndex = mergeItem.row,
  220. mergeRowspan = mergeItem.rowspan,
  221. mergeColIndex = mergeItem.col,
  222. mergeColspan = mergeItem.colspan;
  223. sheetMerges.push({
  224. s: {
  225. r: mergeRowIndex + beforeRowCount,
  226. c: mergeColIndex
  227. },
  228. e: {
  229. r: mergeRowIndex + beforeRowCount + mergeRowspan - 1,
  230. c: mergeColIndex + mergeColspan - 1
  231. }
  232. });
  233. });
  234. }
  235. footers.forEach(function (rows) {
  236. var item = {};
  237. columns.forEach(function (column) {
  238. item[column.id] = getFooterCellValue($table, options, rows, column);
  239. });
  240. footList.push(item);
  241. });
  242. }
  243. var exportMethod = function exportMethod() {
  244. var workbook = new ExcelJS.Workbook();
  245. var sheet = workbook.addWorksheet(sheetName);
  246. workbook.creator = 'vxe-table';
  247. sheet.columns = sheetCols;
  248. if (isHeader) {
  249. sheet.addRows(colList).forEach(function (excelRow) {
  250. if (useStyle) {
  251. setExcelRowHeight(excelRow, rowHeight);
  252. }
  253. excelRow.eachCell(function (excelCell) {
  254. var excelCol = sheet.getColumn(excelCell.col);
  255. var column = $table.getColumnById(excelCol.key);
  256. var headerAlign = column.headerAlign,
  257. align = column.align;
  258. setExcelCellStyle(excelCell, headerAlign || align || allHeaderAlign || allAlign);
  259. if (useStyle) {
  260. Object.assign(excelCell, {
  261. font: {
  262. bold: true,
  263. color: {
  264. argb: defaultCellFontColor
  265. }
  266. },
  267. fill: {
  268. type: 'pattern',
  269. pattern: 'solid',
  270. fgColor: {
  271. argb: defaultHeaderBackgroundColor
  272. }
  273. },
  274. border: getDefaultBorderStyle()
  275. });
  276. }
  277. });
  278. });
  279. }
  280. sheet.addRows(rowList).forEach(function (excelRow) {
  281. if (useStyle) {
  282. setExcelRowHeight(excelRow, rowHeight);
  283. }
  284. excelRow.eachCell(function (excelCell) {
  285. var excelCol = sheet.getColumn(excelCell.col);
  286. var column = $table.getColumnById(excelCol.key);
  287. var align = column.align;
  288. setExcelCellStyle(excelCell, align || allAlign);
  289. if (useStyle) {
  290. Object.assign(excelCell, {
  291. font: {
  292. color: {
  293. argb: defaultCellFontColor
  294. }
  295. },
  296. border: getDefaultBorderStyle()
  297. });
  298. }
  299. });
  300. });
  301. if (isFooter) {
  302. sheet.addRows(footList).forEach(function (excelRow) {
  303. if (useStyle) {
  304. setExcelRowHeight(excelRow, rowHeight);
  305. }
  306. excelRow.eachCell(function (excelCell) {
  307. var excelCol = sheet.getColumn(excelCell.col);
  308. var column = $table.getColumnById(excelCol.key);
  309. var footerAlign = column.footerAlign,
  310. align = column.align;
  311. setExcelCellStyle(excelCell, footerAlign || align || allFooterAlign || allAlign);
  312. if (useStyle) {
  313. Object.assign(excelCell, {
  314. font: {
  315. color: {
  316. argb: defaultCellFontColor
  317. }
  318. },
  319. border: getDefaultBorderStyle()
  320. });
  321. }
  322. });
  323. });
  324. }
  325. if (useStyle && sheetMethod) {
  326. var sParams = {
  327. options: options,
  328. workbook: workbook,
  329. worksheet: sheet,
  330. columns: columns,
  331. colgroups: colgroups,
  332. datas: datas,
  333. $table: $table
  334. };
  335. sheetMethod(sParams);
  336. }
  337. sheetMerges.forEach(function (_ref) {
  338. var s = _ref.s,
  339. e = _ref.e;
  340. sheet.mergeCells(s.r + 1, s.c + 1, e.r + 1, e.c + 1);
  341. });
  342. workbook.xlsx.writeBuffer().then(function (buffer) {
  343. var blob = new Blob([buffer], {
  344. type: 'application/octet-stream'
  345. }); // 导出 xlsx
  346. downloadFile(params, blob, options);
  347. if (showMsg && modal) {
  348. modal.close(msgKey);
  349. modal.message({
  350. content: t('vxe.table.expSuccess'),
  351. status: 'success'
  352. });
  353. }
  354. });
  355. };
  356. if (showMsg && modal) {
  357. modal.message({
  358. id: msgKey,
  359. content: t('vxe.table.expLoading'),
  360. status: 'loading',
  361. duration: -1
  362. });
  363. setTimeout(exportMethod, 1500);
  364. } else {
  365. exportMethod();
  366. }
  367. }
  368. function downloadFile(params, blob, options) {
  369. var $table = params.$table;
  370. var $vxe = $table.$vxe;
  371. var modal = $vxe.modal,
  372. t = $vxe.t;
  373. var message = options.message,
  374. filename = options.filename,
  375. type = options.type;
  376. var showMsg = message !== false;
  377. if (window.Blob) {
  378. if (navigator.msSaveBlob) {
  379. navigator.msSaveBlob(blob, "".concat(filename, ".").concat(type));
  380. } else {
  381. var linkElem = document.createElement('a');
  382. linkElem.target = '_blank';
  383. linkElem.download = "".concat(filename, ".").concat(type);
  384. linkElem.href = URL.createObjectURL(blob);
  385. document.body.appendChild(linkElem);
  386. linkElem.click();
  387. document.body.removeChild(linkElem);
  388. }
  389. } else {
  390. if (showMsg && modal) {
  391. modal.alert({
  392. content: t('vxe.error.notExp'),
  393. status: 'error'
  394. });
  395. }
  396. }
  397. }
  398. function checkImportData(tableFields, fields) {
  399. return fields.some(function (field) {
  400. return tableFields.indexOf(field) > -1;
  401. });
  402. }
  403. function importError(params) {
  404. var $table = params.$table,
  405. options = params.options;
  406. var $vxe = $table.$vxe,
  407. _importReject = $table._importReject;
  408. var showMsg = options.message !== false;
  409. var modal = $vxe.modal,
  410. t = $vxe.t;
  411. if (showMsg && modal) {
  412. modal.message({
  413. content: t('vxe.error.impFields'),
  414. status: 'error'
  415. });
  416. }
  417. if (_importReject) {
  418. _importReject({
  419. status: false
  420. });
  421. }
  422. }
  423. function importXLSX(params) {
  424. var $table = params.$table,
  425. columns = params.columns,
  426. options = params.options,
  427. file = params.file;
  428. var $vxe = $table.$vxe,
  429. _importResolve = $table._importResolve;
  430. var modal = $vxe.modal,
  431. t = $vxe.t;
  432. var showMsg = options.message !== false;
  433. var fileReader = new FileReader();
  434. fileReader.onerror = function () {
  435. importError(params);
  436. };
  437. fileReader.onload = function (evnt) {
  438. var tableFields = [];
  439. columns.forEach(function (column) {
  440. var field = column.property;
  441. if (field) {
  442. tableFields.push(field);
  443. }
  444. });
  445. var workbook = new ExcelJS.Workbook();
  446. var readerTarget = evnt.target;
  447. if (readerTarget) {
  448. workbook.xlsx.load(readerTarget.result).then(function (wb) {
  449. var firstSheet = wb.worksheets[0];
  450. if (firstSheet) {
  451. var sheetValues = firstSheet.getSheetValues();
  452. var fieldIndex = _xeUtils["default"].findIndexOf(sheetValues, function (list) {
  453. return list && list.length > 0;
  454. });
  455. var fields = sheetValues[fieldIndex];
  456. var status = checkImportData(tableFields, fields);
  457. if (status) {
  458. var records = sheetValues.slice(fieldIndex).map(function (list) {
  459. var item = {};
  460. list.forEach(function (cellValue, cIndex) {
  461. item[fields[cIndex]] = cellValue;
  462. });
  463. var record = {};
  464. tableFields.forEach(function (field) {
  465. record[field] = _xeUtils["default"].isUndefined(item[field]) ? null : item[field];
  466. });
  467. return record;
  468. });
  469. $table.createData(records).then(function (data) {
  470. var loadRest;
  471. if (options.mode === 'insert') {
  472. loadRest = $table.insertAt(data, -1);
  473. } else {
  474. loadRest = $table.reloadData(data);
  475. }
  476. return loadRest.then(function () {
  477. if (_importResolve) {
  478. _importResolve({
  479. status: true
  480. });
  481. }
  482. });
  483. });
  484. if (showMsg && modal) {
  485. modal.message({
  486. content: t('vxe.table.impSuccess', [records.length]),
  487. status: 'success'
  488. });
  489. }
  490. } else {
  491. importError(params);
  492. }
  493. } else {
  494. importError(params);
  495. }
  496. });
  497. } else {
  498. importError(params);
  499. }
  500. };
  501. fileReader.readAsArrayBuffer(file);
  502. }
  503. function handleImportEvent(params) {
  504. if (params.options.type === 'xlsx') {
  505. importXLSX(params);
  506. return false;
  507. }
  508. }
  509. function handleExportEvent(params) {
  510. if (params.options.type === 'xlsx') {
  511. exportXLSX(params);
  512. return false;
  513. }
  514. }
  515. /**
  516. * 基于 vxe-table 表格的增强插件,支持导出 xlsx 格式
  517. */
  518. var VXETablePluginExportXLSX = {
  519. install: function install(vxetable) {
  520. var interceptor = vxetable.interceptor;
  521. vxetable.setup({
  522. "export": {
  523. types: {
  524. xlsx: 0
  525. }
  526. }
  527. });
  528. interceptor.mixin({
  529. 'event.import': handleImportEvent,
  530. 'event.export': handleExportEvent
  531. });
  532. }
  533. };
  534. _exports.VXETablePluginExportXLSX = VXETablePluginExportXLSX;
  535. if (typeof window !== 'undefined' && window.VXETable && window.VXETable.use) {
  536. window.VXETable.use(VXETablePluginExportXLSX);
  537. }
  538. var _default = VXETablePluginExportXLSX;
  539. _exports["default"] = _default;
  540. });