util.controller.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { Controller, Body, Fields, Files, Post, Inject } from '@midwayjs/core';
  2. import { Context } from '@midwayjs/koa';
  3. import { ApiTags } from '@midwayjs/swagger';
  4. import { UtilService } from '../service/util.service';
  5. const Excel = require('exceljs');
  6. @ApiTags(['工具'])
  7. @Controller('/util')
  8. export class UtilController {
  9. @Inject()
  10. service: UtilService;
  11. @Inject()
  12. ctx: Context;
  13. @Post('/toExport')
  14. async toExport(@Body() data: object) {
  15. const result = await this.service.toExport(data);
  16. return result;
  17. }
  18. @Post('/toImport')
  19. async upload(@Files() files, @Fields() fields) {
  20. const workbook = new Excel.Workbook();
  21. await workbook.xlsx.read(files);
  22. const result = [];
  23. const sheetList = [];
  24. workbook.eachSheet(sheet => {
  25. // 整理出的数据
  26. const rows = [];
  27. sheet.eachRow((row, ri) => {
  28. if (ri !== 1) {
  29. const rd = [null];
  30. row.eachCell({ includeEmpty: true }, c => {
  31. const value = c.value;
  32. rd.push(value);
  33. });
  34. rows.push(rd);
  35. }
  36. });
  37. sheetList.push({ sheet: sheet.name, rows });
  38. });
  39. for (const s of sheetList) {
  40. const { sheet, rows } = s;
  41. const func = this.service.nameToFunction(sheet);
  42. if (!func) continue;
  43. try {
  44. const num = await this.service[func](rows);
  45. result[sheet] = num.result;
  46. result.push({ key: sheet, num: num.result, errorList: num.errorList.join(',') });
  47. } catch (error) {
  48. console.log(error);
  49. result.push({ key: sheet, num: 'error' });
  50. }
  51. }
  52. this.ctx.ok({ data: result });
  53. }
  54. }