Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
Can't render headers after they are sent to the client stream type exceljs in nodejs

I have this function that will run through express.js

controller.js

const {convertJsontoExcel} = require('./convertJsontoExcel');
const Controller = {
        downloadexcel: async (req, res, next) => {
            try {
                const obj = [
                {
                    id: 222,
                    name: class
                },
                {
                    id: 113,
                    name: class2
                }
                ]
                await convertJsontoExcel(req, res, obj)
            } catch (error) {
                const formattedError = {
                    kode: 500,
                    msg: error.message,
                    detail: error.stack
                }
                res.status(500).json(formattedError);
                }
            },
        }
    }
module.exports = Controller;

router.js

const express = require('express');
const router = express.Router();
const controller= require('./controller');

router.use(express.static(__dirname + '/public'));
router.post('/downloadexcel', controller.downloadexcel)

module.exports = router

convertJsontoExcel.js

   const convertJsontoExcel = async (req, res, jsonData) => {
    const workBook = new excel.stream.xlsx.WorkbookWriter({
        stream: res
    });
    const workSheet = workBook.addWorksheet('Laporan');

    // Set the column
    console.log("Set the column")
    workSheet.columns = [
        { header: ' Id', key: 'id', width: 25 },
        { header: ' name', key: 'name', width: 25 },
    ];
    console.log("Looping for adding the data to excel")
    for (let i = 0; i < jsonData.length; i++) {
        const r = i + 1;
        workSheet.addRow(jsonData[i]).commit();
    }

    // console.log("commit")
    // await workBook.commit();
    // await workBook.xlsx.write();
    res.setHeader("Content-Type", "application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet");
    res.setHeader("Content-Disposition", "attachment; filename=Rep1ort.xlsx");
    workBook.xlsx.write(res).then(function () {
        res.status(200).end();
    });
}
module.exports = {
convertJsontoExcel
}

I want to set a download file from generated excel file using exceljs but when i run this code, its always return Error: Can't render headers after they are sent to the client. WHat's wrong with my code ?

Surprisingly, i still can download the file, but the machine will eventually shutdown because unhandled error.

How to set download file for so it can downloaded from browser file ?

about 4 years ago · Santiago Gelvez
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda