excel.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const Excel = require('exceljs');
  7. const { sep } = require('path');
  8. const fs = require('fs');
  9. //
  10. class ExcelService extends CrudService {
  11. constructor(ctx) {
  12. super(ctx, 'excel');
  13. }
  14. // eslint-disable-next-line jsdoc/require-param
  15. /**
  16. * 检查路径,创建路径;返回前端接收路径
  17. * @param {Array} filesPath 地址拆开 例如: ['www','dir','example']
  18. * @return {Object} path 短地址;rPath 文件真实路径
  19. */
  20. checkPath(filesPath = []) {
  21. const { root_path, project, export_dir } = this.ctx.app.config.filesConfig;
  22. const arr = [ root_path, project, export_dir, ...filesPath ];
  23. let rPath = '';
  24. for (const i of arr) {
  25. rPath = `${rPath}${i}${sep}`;
  26. if (!fs.existsSync(rPath)) {
  27. fs.mkdirSync(rPath);
  28. }
  29. }
  30. arr.shift();
  31. arr.unshift('files');
  32. const path = `/${arr.join('/')}`;
  33. return { path, rPath };
  34. }
  35. /**
  36. * 将短地址转换为真实地址
  37. * @param {String} path 短地址
  38. */
  39. toRealPath(path) {
  40. const r = path.includes('/files');
  41. if (!r) return path;
  42. const { root_path } = this.ctx.app.config.filesConfig;
  43. const rPath = _.replace(path, '/files', root_path);
  44. return rPath;
  45. }
  46. /**
  47. * 导入,读取excel文件
  48. * @param {String} path 导入的文件短地址
  49. * @return {Array[Array]} values 二维数组,外维:行;第二维:列
  50. */
  51. async importExcel(path) {
  52. const realPath = this.toRealPath(path);
  53. const workbook = new Excel.Workbook();
  54. await workbook.xlsx.readFile(realPath);
  55. const sheet = workbook.getWorksheet(1);
  56. const values = [];
  57. sheet.eachRow(row => {
  58. const data = row.values;
  59. // 第一列是空的,扔了
  60. data.shift();
  61. values.push(data);
  62. });
  63. return values;
  64. }
  65. }
  66. module.exports = ExcelService;