how to download excel in adonis js

36 views Asked by At

I want to download excel using below code. Are there any easy way to download excel?

const filename = request.input('filename')
const users = await User.all()
const columnKeys = Object.keys(users[0].$attributes);
const columns = columnKeys.map(key => ({ header: key.charAt(0).toUpperCase() + key.slice(1), key, width: 32 }));

const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet(filename)

worksheet.columns = columns;
 
users.forEach(user => {
    worksheet.addRow(user.$attributes)
})
     
// await workbook.xlsx.writeFile(`${filename}.xlsx`);
// Generate the Excel file and get it as a buffer
const buffer = await workbook.xlsx.writeBuffer();

// Write the buffer to a file
// const fs = require('fs');
// const  rrr = fs.writeFileSync(Application.tmpPath('uploads', `${filename}.xlsx`), buffer);


// Set the response headers
response.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response.header('Content-Disposition', `attachment; filename=${filename}.xlsx`)

// Return the buffer as a response
return response.send(buffer)
0

There are 0 answers