提问者:小点点

NodeJS Excel文件生成问题


我正在尝试将json转换为NodeJS中的xlsx文件。 并且下面的代码工作得很完美,除了它对表的最后一列进行分组之外。由于我没有使用任何命令来添加分组pf列,我如何删除它呢?

null

self.getTransactionsExport = function (req, res, next) {
  console.log('-----getTransactionsFieldsList()-----', req.body);

  const params = [
    req.body.date,
    req.body.id,
    req.body.com_id
  ];

  var fields = [
    { prop: 'date', fieldName:'Date'},
    { prop: 'type', fieldName:'Type'},
    { prop: 'no', fieldName:'Reference No.'},
    { prop: 'inv_am', fieldName:'Invoice Amount'},
    { prop: 'paid_am', fieldName:'Paid Amount'},
    { prop: 'balance', fieldName:'Balance'}
  ];
  const query = `select * from ${dbSchema}.f_transaction(${params.map((el, i) => '$' + ++i).join(',')});`;

  console.log('~~~~~~~~ ]\n\n', query, params);

  db.query(query, params).then((data) => {
    console.log('result search export: ', data.rowCount);
    console.log('result: ', data.rows.length);
    if (data.rows.length) {
      let workbook = new excel.Workbook(); //creating workbook
      let worksheet = workbook.addWorksheet('Transactions'); // creating worksheet
      const jsonCustomers = JSON.parse(JSON.stringify(data.rows));
      const columns = fields.map((el, i, arr) => {
        const newEl = {header: el.fieldName, key: el.prop};
        if (i === arr.length -1) {
          Object.assign(newEl, {outlineLevel: 1});
        }
        return newEl;
      });
      worksheet.columns = columns;
      const filename = `Transations_${req.body.current_date}.xlsx`.split(' ').join('_');
      // Add Array Rows
      worksheet.addRows(jsonCustomers);
      res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition'); // <-- very important to allow read filename and download on frontend
      res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

      return workbook.xlsx.write(res).then(() => {
        res.status(200).end();
      }).catch((error) => {
        console.error(`Excel failed: `, error);
      });

    } else {
      res.status(400).json({status: 'No Result', message: 'No result from DB'});
    }
  }).catch((err) => {
    res.status(500).json({status: 'ERROR', message: err.toString()});
  });
};

null


共1个答案

匿名用户

以下代码正在生成最后一列分组:

if (i === arr.length -1) {
      Object.assign(newEl, {outlineLevel: 1});
    }

解决办法是:

  1. if(i===arr.length-1){object.assign(newEl,{outlineLevel:0});}