xlsx-service.js 887 Bytes
/**
 * Created by TaoHuang on 2017/5/17.
 */
const Context = require('../framework/context');
const xlsx2json = require('xlsx2json');
const Api = require('../common/api');
const _ = require('lodash');

class XlsxService extends Context {
  constructor() {
    super();
    this.api = this.instance(Api);
  }
  resolveExcel(path, cols) {
    return xlsx2json(path).then(excelData => {
      const sheetData = _.first(excelData);
      const header = sheetData[0];
      const rows = _.slice(sheetData, 1);
      const columns = _.map(cols, (v, k) => {
        return {
          key: k,
          col: _.findKey(header, hv => _.trim(hv) === v),
        };
      });

      return _.map(rows, row => {
        const item = {};

        _.each(columns, col => {
          item[col.key] = row[col.col];
        });
        return item;
      });
    });
  }
}

module.exports = XlsxService;