Downloading data in excel format with Nest.js

import {Controller, Get, Header, Res} from '@nestjs/common';
import { ExcelService } from './excel.service';
import {Response} from "express";

@Controller('excel')
export class ExcelController {
constructor(private readonly excelService: ExcelService) {}

@Get('/download')
@Header('Content-Type', 'text/xlsx')
async downloadReport(@Res() res: Response) {
let data = [
{
'name':'ali',
'lname':'aliii',
},
{
'name':'reza',
'lname':'rezazzz',
},
{
'name':'hassan',
'lname':'hassini',
}
];

let merges = ['A2:A3' , 'B2:B3' ];
let header =
[
'name222',
'lname333',
]
;
let result = await this.excelService.downloadExcel(header, data, merges);

res.download(`${result}`);
}

}
import { HttpException, HttpStatus, Injectable} from '@nestjs/common';
import * as tmp from 'tmp';
import {Workbook} from "exceljs";

@Injectable()
export class ExcelService {

/**
* downloadExcel
*
@param header
*
@param data
*
@param merges
*/
async downloadExcel( header: string[]= [], data: object[]= [], merges: string[]= []){
if( !data.length ){
throw new HttpException(
'no data for download',
HttpStatus.BAD_REQUEST,
);
}

let rows = [];

rows.push(header);

data.forEach( doc=>{
rows.push(Object.values(doc));
})

let book = new Workbook();

let sheet = book.addWorksheet('sheet1' ,{views:[{ rightToLeft: true}]})


sheet.addRows( rows);

if(merges.length){
for(let merge of merges){
sheet.mergeCells(merge)
}
}



let file = await new Promise( ( resolve, reject) => {
tmp.file(
{discardDescriptor: true, perfix: 'MyExcelSheet', postfix: '.xlsx', mode: parseInt('0600', 8)},
async (err, file) => {
book.xlsx.writeFile(file).then(_ => {
resolve(file);
}).catch(err => {
throw new HttpException(
'data is invalid',
HttpStatus.BAD_REQUEST,
);
})

}
)
}
);





return file;
}

}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store