首页 > 解决方案 > 解析 XLSX 并转换为对象

问题描述

这是一个图片链接。这是一个 XLXS 文件,我正在尝试将其转换为 JSON 格式。每个父母都应该有两个键名和孩子(孩子键是数组类型,包含所有孩子)

标签: node.jsjson

解决方案


你可以试试exceljs库。

例子:

class MyExcelSheetHelper {

  constructor() {

    const ExcelJS = require('exceljs');
    this.workbook = new ExcelJS.Workbook();    
    this.worksheet = this.workbook.addWorksheet('Report name', {properties:{tabColor:{argb:'FFC0000'}}});    
  }

  startHeader(){

    this.worksheet.columns = [
      { header: 'Data criado', key: 'datetime', width: 25 },
      { header: 'Data inicio', key: 'dateStart', width: 25 },
      { header: 'Data fim', key: 'dateEnd', width: 25 },
      { header: 'Profissional', key: 'worker', width: 25 },      
      { header: 'Cliente', key: 'client', width: 25 },
      { header: 'Origem', key: 'from', width: 100 },
      { header: 'Destino', key: 'to', width: 100 },
      { header: 'Referência', key: 'reference', width: 25 },                  
      { header: 'Serviço', key: 'job', width: 25 },            
      { header: 'Valor total', key: 'total', width: 25 },
      { header: 'Qualificação', key: 'rate', width: 25 },
      { header: 'Status', key: 'status', width: 25 }
    ];
  }


}

然后:

function startReport(querySnapshot) { 

  const excelFileHelper = new MyExcelSheetHelper();
  const worksheet = excelFileHelper.worksheet;  

  excelFileHelper.startHeader()

  querySnapshot.forEach(entrySnapshot => {   

    const payload = entrySnapshot.val();

    worksheet.addRow({
      id: 1,
      datetime: moment(payload.datetime).format("DD/MM/YYYY hh:mm:ss"),
      dateStart: moment(payload.datetimeStart).format("DD/MM/YYYY hh:mm:ss"),
      dateEnd: moment(payload.datetimeFinish).format("DD/MM/YYYY hh:mm:ss"),
      worker: payload.workerInfo.name,
      client: payload.clientInfo.name,
      from: payload.clientInfo.fromAddress,
      to: payload.clientInfo.toAddress,                              
      reference: payload.clientInfo.reference,
      job: payload.clientInfo.serviceSelected,
      total: payload.clientInfo.total,
      rate: payload.clientInfo.rate,
      status: payload.clientInfo.status
    });



  });  

  let datetime = moment().format("DDMMYYYHHmmss")
  let pathFinal = 'Relatorio_' + datetime + '.xlsx'  

  return excelFileHelper.salva(pathFinal);
}

推荐阅读