excelUtils.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. const Excel = require('exceljs');
  3. const utils = {
  4. // 定义格式: 工作表
  5. // [ {sheetName:''} , {} ]
  6. // 获取excel
  7. getExcel(config) {
  8. if (!config) {
  9. return;
  10. }
  11. const workbook = new Excel.Workbook();
  12. config.forEach((con, index) => {
  13. const ws1 = workbook.addWorksheet(con.sheetName || 'sheet' + index, con.sheetOptions);
  14. con.sheetHeader.forEach(header => {
  15. const row = ws1.addRow([ header.headerName ]);
  16. Object.keys(header.headerConfig).forEach(key => {
  17. row[key] = header.headerConfig[key];
  18. });
  19. });
  20. ws1.mergeCells(con.sheetKey[0].letter + '1:'
  21. + con.sheetKey[con.sheetKey.length - 1].letter + '1');
  22. ws1.addRow(con.sheetKey.map(item => item.label));
  23. con.sheetData.forEach((data, index) => {
  24. const rowData = con.sheetKey.map((item, i) => {
  25. ws1.getColumn(i + 1).width = item.width;
  26. if (item.key == 'num') {
  27. return index + 1;
  28. }
  29. // console.log('====================', item)
  30. // if (item.key == 'birthday') {
  31. // const myDate = new Date();
  32. // const year = myDate.getFullYear();
  33. // const month = (myDate.getMonth() + 1) > 9 ? (myDate.getMonth() + 1) : '0' + (myDate.getMonth() + 1);
  34. // const day = myDate.getDate() > 9 ? (myDate.getDate()) : '0' + (myDate.getDate());
  35. // return item.value = ;
  36. // }
  37. return this.getValue(data, item) || '';
  38. });
  39. ws1.addRow(rowData);
  40. });
  41. const tableKeyHeader = 1;
  42. const tableFirst = 1;
  43. this.rowCenter(ws1, tableFirst,
  44. con.sheetData.length + con.sheetHeader.length + tableKeyHeader);
  45. });
  46. return workbook;
  47. },
  48. rowCenter(arg_ws, arg_start, arg_end) {
  49. for (let i = arg_start; i <= arg_end; i++) {
  50. arg_ws.findRow(i).alignment = { vertical: 'middle', horizontal: 'center' };
  51. arg_ws.findRow(i).eachCell(function(cell, index) {
  52. if (i == 1) {
  53. cell.font = { bold: true };
  54. } else {
  55. cell.font = { bold: false };
  56. }
  57. cell.border = {
  58. top: { style: 'thin' },
  59. left: { style: 'thin' },
  60. bottom: { style: 'thin' },
  61. right: { style: 'thin' },
  62. };
  63. });
  64. }
  65. },
  66. getValue(data, config) {
  67. if (config.key.indexOf('.') != -1) { // 存在子属性
  68. const props = config.key.split('.');
  69. return props.reduce((first, second) => {
  70. if (first) {
  71. return first[second];
  72. }
  73. return null;
  74. }, data);
  75. } // 不存在
  76. return data[config.key];
  77. },
  78. };
  79. module.exports = utils;