excel.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const _ = require('lodash');
  3. const { sep } = require('path');
  4. const fs = require('fs');
  5. const Excel = require('exceljs');
  6. const moment = require('moment');
  7. const { CrudService } = require('naf-framework-mongoose/lib/service');
  8. const { BusinessError, ErrorCode } = require('naf-core').Error;
  9. class ExcelService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx);
  12. this.root_path = _.get(this.ctx.app.config.export, 'root_path');
  13. this.file_type = 'export';
  14. if (!fs.existsSync(`${this.root_path}${this.file_type}`)) {
  15. // 如果不存在文件夹,就创建
  16. fs.mkdirSync(`${this.root_path}${this.file_type}`);
  17. }
  18. this.excel_path = `${sep}excel${sep}`;
  19. }
  20. /**
  21. * 导出excel;
  22. * @param {Object} param { data, meta, fn }
  23. * @property Object data 数据;有meta的形式就是正常数据直接用;没有meta情况,需要整理成行数据
  24. * @property meta 列设置; 若meta不存在,则逐行解析. meta存在,则直接自动解析
  25. * @property fn 文件名
  26. */
  27. async toExcel({ data = [], meta, fn = 'excel导出结果' } = {}) {
  28. console.log('in function:');
  29. const nowDate = new Date().getTime();
  30. const filename = `${fn}.xlsx`; // -${nowDate}
  31. const path = `${this.root_path}${this.file_type}${this.excel_path}`;
  32. if (!path) {
  33. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  34. }
  35. if (!fs.existsSync(path)) {
  36. // 如果不存在文件夹,就创建
  37. fs.mkdirSync(path);
  38. }
  39. const workbook = new Excel.Workbook();
  40. const sheet = workbook.addWorksheet('sheet');
  41. if (meta) {
  42. sheet.columns = meta;
  43. sheet.addRows(data);
  44. } else {
  45. console.log(data);
  46. for (const row of data) {
  47. const { scell, ecell, content, alignment } = row;
  48. if (scell && ecell) sheet.mergeCells(scell, ecell);
  49. sheet.getCell(ecell).value = content;
  50. if (alignment) sheet.getCell(ecell).alignment = alignment;
  51. }
  52. // sheet.mergeCells(1,1,1,2); //合并单元格,起始行,列 ,终止行,列
  53. }
  54. // 导出
  55. const filepath = `${path}${filename}`;
  56. if (data.length <= 0) return;
  57. await workbook.xlsx.writeFile(filepath);
  58. }
  59. numberToLetter(num) {
  60. const arr = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z' ];
  61. return arr[num];
  62. }
  63. }
  64. module.exports = ExcelService;