[NestJS] create excel download by exceljs

Programming/Node.js 2024. 12. 6. 23:00 Posted by 생각하는로뎅
반응형

1. exceljs 를 받는다.

npm install exceljs

 

 

2. controller 에 작성한다.

this is controller.ts

import { Res, Req, Get } from '@nestjs/common';
import * as ExcelJS from 'exceljs';

...

// 엑셀 다운로드
@Get('downloadExcel')
async downloadExcel(
  @Req() req : Request
, @Res() res : Response ) {

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

    worksheet.columns = [
        { header: 'name', key: 'name' },
        { header: 'age', key: 'age' }
    ];

    worksheet.addRow({
        name: 'test Row',
        age: 37
    });

    const buffer = await workbook.xlsx.writeBuffer();
    res.header('Content-Disposition', 'attachment; filename=data.xlsx');
    res.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.send(buffer);

}

 

3. html

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    .....

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    .....
    
</head>

<body>
...

	<button type="button" id="download_excel">엑셀다운로드</button>
...
</body>

<script>

// 엑셀 다운로드 버튼 클릭
$("#download_excel").click(function () {

    axios({
        method: "get",
        url: "/downloadExcel",
        responseType: "blob", 
    })
    .then((response) => {
        const url = window.URL.createObjectURL(
        new Blob([response.data])
        );
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "data.xlsx"); 
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    })
    .catch((error) => {
    });

});
            
</script>

 

 


 

Nestjs export Excel file

The full stack explains export excel so easy, using nestjs, exceljs, axios

medium.com

 

반응형