Search code examples
javascriptexceljsfastify

how can i use exceljs in fastify?


I use exceljs like this but it returns a error.

TypeError: pipe.write is not a function

and

"message": "Cannot read property 'summary' of undefined"

let workbook = new Excel.Workbook()
  let worksheet = workbook.addWorksheet('calogs')
  worksheet.columns = [
    {header: 'id', key: 'id', width: 5 },
    ...
  ]
  // Add Array Rows
  worksheet.addRows(data)
  console.log('XXXXXXXXXXXXXXXXXXXXX',worksheet)
  // res is a Stream object???
  reply.header(
    'Content-Type',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  )
  reply.header(
    'Content-Disposition',
    `attachment; filename=` +`calogs.xlsx`
  )
  
  return workbook.xlsx.write(reply).then(function() {
    reply.status(200).end()
  })

how can i fix it?


Solution

  • The reply object is not a stream, you could try reply.raw that is the raw HTTP Server Response.

    Anyway, the reply could manage this for you, here an example with xlsx module:

    const XLSX = require('xlsx')
    const fastify = require('fastify')()
    
    fastify.get('/', function (request, reply) {
      const wb = XLSX.utils.book_new()
      const wsName = 'SheetJS'
      const wsData = [
        ['S', 'h', 'e', 'e', 't', 'J', 'S'],
        [1, 2, 3, 4, 5]
      ]
      const ws = XLSX.utils.aoa_to_sheet(wsData)
    
      XLSX.utils.book_append_sheet(wb, ws, wsName)
    
      const wopts = { bookType: 'xlsx', bookSST: false, type: 'buffer' }
      const wBuffer = XLSX.write(wb, wopts)
    
      reply.header('Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      )
      reply.header('Content-Disposition',
        'attachment; filename=' + 'calogs.xlsx'
      )
      reply.send(wBuffer)
    })
    
    fastify.listen(8080)