Egg. js 에서 exceljs 내 보 내기

excel 내 보 낼 때 많은 배경 관리 시스템 에 필요 한 기능 을 연구 하고 자 한다. 본 고 는 주로 egg. js 를 바탕 으로 하 는 시스템 에서 exceljs 를 봉인 하여 excel 내 보 내기 를 크게 간소화 한다.
여기 서 우 리 는 helper 를 확장 하여 코드 를 직접 올 립 니 다.
const Excel = require('exceljs');

  /**
   *            excel
   *        (m1:         ;m2:         )
   *         totalRowText totalRow
   *          func
   *        
   *      
   * @param {string} url     :      http       
   * @param {object} req     
   * @param {Array} headers excel   
   * @param {string} name     
   * @param {function} func        
   */
  async excelNew(url, req, headers, name, func) {
    let columns = [];//exceljs   columns
    let hjRow = {};//   
    let titleRows = headers.length;//     

    //    
    for (let i = 0; i < titleRows; i++) {
      let row = headers[i];
      for (let j = 0, rlen = row.length; j < rlen; j++) {
        let col = row[j];
        let { f, t, w = 15 } = col;
        if (!f) continue;//   f   

        if (col.totalRow) hjRow[f] = true;
        if (col.totalRowText) hjRow[f] = col.totalRowText;
        col.style = { alignment: { vertical: 'middle', horizontal: 'center' } };
        col.header = t;
        col.key = f;
        col.width = w;
        columns.push(col);
      }
    }

    const result = await this.post(url, req);//    
    let data = result.data;
    if (func) data = func(data);

    //     
    if (JSON.stringify(hjRow) != "{}") {
      let tr = {};
      for (let i = 0, len = data.data.length; i < len; i++) {
        let item = data.data[i];
        for (let key in item) {
          if (hjRow[key] === true) {
            tr[key] = (tr[key] || 0) + item[key];
            continue;
          }
          tr[key] = hjRow[key] || '';
        }
      }
      data.data.push(tr);
    }

    let workbook = new Excel.Workbook();
    let sheet = workbook.addWorksheet('My Sheet', { views: [{ xSplit: 1, ySplit: 1 }] });
    sheet.columns = columns;
    sheet.addRows(data.data);

    //      
    if (titleRows > 1) {
      for (let i = 1; i < titleRows; i++)  sheet.spliceRows(1, 0, []);//      

      for (let i = 0; i < titleRows; i++) {
        let row = headers[i];
        for (let j = 0, rlen = row.length; j < rlen; j++) {
          let col = row[j];
          if (!col.m1) continue;

          sheet.getCell(col.m1).value = col.t;
          sheet.mergeCells(col.m1 + ":" + col.m2);
        }
      }
    }

    //    、  、   
    let that = this;
    sheet.eachRow(function (row, rowNumber) {
      //    
      row.height = 25;
      
      row.eachCell({ includeEmpty: true }, function (cell, colNumber) {
        //           
        let top = left = bottom = right = { style: 'thin', color: { argb: '000000' } };
        cell.border = { top, left, bottom, right };

        //         
        if (rowNumber <= titleRows) { cell.font = { bold: true };  return; }

        //             
        let {type,dict} = columns[colNumber - 1];
        if (type && (cell.value || cell.value == 0)) return;//   、           
        switch(type){
          case 'date': cell.value = that.parseDate(cell.value);break;
          case 'dict': cell.value = that.parseDict(cell.value.toString(), dict);break;
        }

      });
    });

    this.ctx.set('Content-Type', 'application/vnd.openxmlformats');
    this.ctx.set('Content-Disposition', "attachment;filename*=UTF-8' '" + encodeURIComponent(name) + '.xlsx');
    this.ctx.body = await workbook.xlsx.writeBuffer();
  }

사용 방법:
async excel(ctx) {
    let req = ctx.helper.data(['strBeginTime', 'strEndTime', 'deptId']);
    req.deptId = req.deptId || ctx.session.user.deptId;

    let headers = [[
      { t: '    ',f: 'deptName', w: 20, m1:'A1',m2:'A3',totalRowText: '  '},
      { t: '       ',m1:'B1',m2:'M1'},
      { t: '       ', m1:'N1',m2:'O1' },
      { t: '  ', m1:'P1',m2:'R2' }
    ], [
      { t: '  ', m1:'B2',m2:'D2' },
      { t: '  ', m1:'E2',m2:'G2' },
      { t: '  ', m1:'H2',m2:'J2' },
      { t: '  ', m1:'K2',m2:'M2' },
      { t: '     ', m1:'N2',m2:'O2' }
    ], [
      { t: '    ', f: 'slbdCount', totalRow: true },
      { t: '    ', f: 'slydCount', totalRow: true },
      { t: '  ', f: 'slJe', totalRow: true },
      { t: '    ', f: 'hlbdCount', totalRow: true },
      { t: '    ', f: 'hlydCount', totalRow: true },
      { t: '  ', f: 'hlJe', totalRow: true },
      { t: '    ', f: 'blbdCount', totalRow: true },
      { t: '    ', f: 'blydCount', totalRow: true },
      { t: '  ', f: 'blJe', totalRow: true },
      { t: '    ', f: 'xj_bdrs', totalRow: true },
      { t: '    ', f: 'xj_ydrs', totalRow: true },
      { t: '  ', f: 'xj_je', totalRow: true },
      { t: '  ', f: 'lsCount', totalRow: true },
      { t: '  ', f: 'lsJe', totalRow: true },
      { t: '    ', f: 'hj_bdrs', totalRow: true },
      { t: '    ', f: 'hj_ydrs', totalRow: true },
      { t: '  ', f: 'hj_je', totalRow: true }
    ]];
    await ctx.helper.excelNew('/bill/querySfzbb', req, headers, '       ',function(res){
        for (let i = 0, len = res.data.length; i < len; i++) {
          let r = res.data[i];
          r.xj_bdrs = r.slbdCount + r.hlbdCount + r.blbdCount;
          r.xj_ydrs = r.slydCount + r.hlydCount + r.blydCount;
          r.xj_je = r.slJe + r.hlJe + r.blJe;
          r.hj_bdrs = r.slbdCount + r.hlbdCount + r.blbdCount + r.lsCount;
          r.hj_ydrs = r.slydCount + r.hlydCount + r.blydCount;
          r.hj_je = r.slJe + r.hlJe + r.blJe + r.lsJe;
      }
      return res;
    });
  }

좋은 웹페이지 즐겨찾기