excel.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. const ExcelJS = require('exceljs');
  4. class ExcelService extends Service {
  5. // 创建
  6. async establish({ fileName, type, _this }) {
  7. const workbook = new ExcelJS.Workbook();
  8. const sheet = workbook.addWorksheet('Sheet');
  9. const exportFiled = _this.app.config.exportFiled[`export${type}`];
  10. sheet.columns = exportFiled.map(e => ({ header: e.title, key: e.name, width: 30 }));
  11. return await workbook.xlsx.writeFile(`${_this.app.config.exportsPath}/${fileName}.xlsx`).then(function() {
  12. return 'success';
  13. }, function(err) {
  14. return err;
  15. });
  16. }
  17. // 写入
  18. async insertFile({ type, data, fileName, _this }) {
  19. const filename = `${_this.app.config.exportsPath}/${fileName}.xlsx`;
  20. const workbook = new ExcelJS.Workbook();
  21. const exportFiled = _this.app.config.exportFiled[`export${type}`];
  22. // 读取文件
  23. await workbook.xlsx.readFile(filename)
  24. .then(async function() {
  25. // 获取sheet
  26. const worksheet = workbook.getWorksheet(1);
  27. // 遍历数据
  28. data.forEach(e => {
  29. // 获取左后可编辑行
  30. const lastRow = worksheet.lastRow;
  31. // 获取最后一行加一
  32. const getRowInsert = worksheet.getRow(lastRow.number + 1);
  33. // 遍历头文件 为制造单元格下表
  34. for (let i = 0; i < exportFiled.length; i++) {
  35. // 向最后一行加一的行 对应的单元格内添加数据
  36. getRowInsert.getCell(i + 1).value = e[exportFiled[i].name] || '';
  37. }
  38. getRowInsert.commit();
  39. });
  40. await workbook.xlsx.writeFile(filename);
  41. });
  42. }
  43. }
  44. module.exports = ExcelService;