node文件流excel导出


  • 文件流导出excel

重点:Content-Disposition 文件名是中文显示
const nodeExcel = require('node-xlsx');
const urlencode = require('urlencode');

function exportList(ctx, config, listData, excelName) {
    let excelConfig = [];
    excelConfig.push(config.map(item => {
      return item.title
    }))

    listData.forEach(list => {
      excelConfig.push(config.map(item => {
        const value = list[item.name];
        // 不一定要有value, 因为可能是自由组合的value
        return item.format && item.format(value, list) || value;
      }))
    })

    let buffer = nodeExcel.build([{name: excelName, data: excelConfig}]);
    ctx.set('Content-Type', 'application/octet-stream');
     // ctx.request.headers['user-agent']
    let name = urlencode(excelName + '_' + (+new Date()) + '.xlsx', "utf-8");
    ctx.set("Content-Disposition", "attachment; filename* = UTF-8''"+name);    
    // ctx.set("Content-Disposition", "attachment; filename="+ (+new Date()) + '.xlsx');
    ctx.body = buffer;
}

module.exports = {
  exportList: exportList
}
// config 格式
const config = [{
      name: 'userid',
      title: '用户ID',
    },{
      name: 'up_time',
      title: '状态时间',
      format: function(value) {
        return value.replace(/\.\d+/, '');
      }
    },{
      name: 'appl_status_byhand',
      // name: 'appl_status_byhand_desc',
      title: '人审状态',
      format: function(value) {
        return value && manualStatus[value] &&  manualStatus[value].text || '-'
      }
    },{
      name: 'available_quota/credit_quota',
      title: '剩余额度/授信额度',
      format: function(value, item) {
        return `¥${item.available_quota/100 || 0}/¥${item.credit_quota/100 || 0}`
      }
    },{
      name: 'user_type_desc',
      title: '名单类型',
      format: function(value, item) {
        if(item.user_type) {
          item.user_type.forEach(user => {
            userTypeText.push(user_type_define[user] || '-');
          });
          return userTypeText.join('|');
        } else {
          return '';
        }
      }
    }]

你可能感兴趣的:(nodejs,buffer)