excelimport.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. const XLSX = require('xlsx');
  3. const Service = require('egg').Service;
  4. class ExcelimportService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.appid = '';
  8. }
  9. // 获取导入的XLSX文件中的数据
  10. async getImportXLSXData(result) {
  11. for (const elem of result) {
  12. const id = elem._id;
  13. const filepath = this.ctx.app.config.fileDirImp + elem.content;
  14. if(elem.type === '0'){
  15. const workbook = XLSX.readFile(filepath);
  16. // 读取内容
  17. let exceldata = [];
  18. const sheetNames = workbook.SheetNames; // 获取表名
  19. const sheet = workbook.Sheets[sheetNames[0]]; // 通过表名得到表对象
  20. const theadRule = [ sheet.A1.v, sheet.B1.v, sheet.C1.v, sheet.D1.v, sheet.E1.v, sheet.F1.v, sheet.G1.v, sheet.H1.v, sheet.I1.v, sheet.J1.v, sheet.K1.v, sheet.L1.v, sheet.M1.v, sheet.N1.v, sheet.O1.v, sheet.P1.v ];
  21. const params = XLSX.utils.sheet_to_json(sheet); // 通过工具将表对象的数据读出来并转成json
  22. // const theadRule = [ '序号', '院系', '班级', '专业代码', '专业名称', '学号', '姓名', '身份证号', '性别', '学历代码', '学历名称', '毕业年份', '民族', '电话号码', '生源所在地', '政治面貌' ];
  23. console.log(params);
  24. if (!params) return [];
  25. let i = 0;
  26. const length = params.length;
  27. const _datas = [];
  28. let data = {};
  29. for (i; i < length; i++) {
  30. data = params[i];
  31. _datas.push({
  32. szyx: data[theadRule[1]],
  33. szbj: data[theadRule[2]],
  34. zydm: data[theadRule[3]],
  35. zymc: data[theadRule[4]],
  36. xh: data[theadRule[5]],
  37. xm: data[theadRule[6]],
  38. sfzh: data[theadRule[7]],
  39. xb: data[theadRule[8]],
  40. xldm: data[theadRule[9]],
  41. xl: data[theadRule[10]],
  42. year: data[theadRule[11]],
  43. mz: data[theadRule[12]],
  44. dhhm: data[theadRule[13]],
  45. syszd: data[theadRule[14]],
  46. zzmm: data[theadRule[15]],
  47. });
  48. }
  49. exceldata = [ ...exceldata, ..._datas ];
  50. console.log(exceldata);
  51. //
  52. const stuPath = this.ctx.app.config.baseDirImp + this.ctx.app.config.stusDirImp;
  53. const queryData = { year: elem.createtime, schid: elem.userid, schname: elem.name};
  54. const studRes = this.ctx.curl(stuPath, {
  55. method: 'POST',
  56. dataType: 'json',
  57. query: queryData,
  58. body: exceldata,
  59. });
  60. console.log(studRes);
  61. // 导入成功时更新状态
  62. if(studRes != null){
  63. const updatedata = {id: id, status: '1' };
  64. await this.ctx.service.dataimp.update(updatedata);
  65. }
  66. }
  67. }
  68. return '0';
  69. }
  70. }
  71. module.exports = ExcelimportService;