Alim Öncül
Alim Öncül

Reputation: 137

How to return an excel file from NestJS Controller

So I am reading lots of data from my mongoose database and writing them into XLSX of SheetJS. I want to return a downloadable file from my controller. I got an object below, question is how can i return this object for download?

const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });

Upvotes: 0

Views: 11077

Answers (2)

Niv Lusty
Niv Lusty

Reputation: 33

you can try to implement it that way:

import {Readable} from "stream";
import {readFileSync} from 'fs';
import {Response} from 'express';

    @Get('')
    async createFile(@Res() res: Response) 
    {
        var buffer = readFileSync('/path_to_file');

        const stream = new Readable();
        stream.push(buffer);
        stream.push(null);

        res.set({
            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Length': buffer.length,
        });
        stream.pipe(res);
    }

Upvotes: 0

Alim Öncül
Alim Öncül

Reputation: 137

I done it with code below. Header prompts a file download, type sets the correct type for file and you can send it with res.send()

res.header('Content-disposition', 'attachment; filename=anlikodullendirme.xlsx');
res.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
return res.send(buffer);

Upvotes: 4

Related Questions