[nest.js] exceljs

김민재·2025년 2월 13일

nest.js

목록 보기
29/63

exceljs란?

  • Excel 파일을 처리하기 위해 사용되는 라이브러리이다. 주로 데이터의 내보내기 및 가져오기 기능을 구현할 때 사용된다.

사용 방법

  • npm install exceljs

코드 service.ts

 async generateExcel(annualLeaveRecords: AnnualLeave[], @Res({ passthrough: true }) response: Response) {
        // ExcelJS 워크북 생성
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('모든 직원 연차 기록');

        // Excel 파일 헤더 정의
        worksheet.columns = [
            { header: '사용자', key: 'userName' },
            { header: '부서', key: 'department' },
            { header: '시작일', key: 'startDate' },
            { header: '종료일', key: 'endDate' },
            { header: '기록', key: 'record' },
        ];

        worksheet.getRow(1).eachCell((cell) => {
            // 첫번째 row만
            (cell.font = { bold: true, color: { argb: 'FFFFFF' } }),
                (cell.alignment = { horizontal: 'center', vertical: 'middle' }),
                (cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: '4CAF50' } });
        });

        // 연차 기록 데이터를 Excel 시트에 추가
        annualLeaveRecords.forEach((annualLeave) => {
            worksheet.addRow({
                userName: annualLeave.user.name,
                department: annualLeave.user.department,
                startDate: annualLeave.start_date,
                endDate: annualLeave.end_date,
                record: annualLeave.record_contents,
            });
        });

        // Excel 파일을 스트림으로 보내기(스트림: 파일을 한 번에 보내는 게 아니라 조각조각 나눠서 보냄)
        response.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        response.setHeader('Content-Disposition', 'attachment; filename=leave-records.xlsx');

        await workbook.xlsx.write(response);
        response.end();
    }

코드 controller.ts

    /**
     * 내 연차 기록 excel 다운 받기
     * @returns
     */
    @UseGuards(JwtAuthGuard)
    @Get(':userId/excel/download/annualLeaves')
    async generateAnnualLeaveExcel(
        @Param('userId') userId: number,
        @Res({ passthrough: true }) response: Response,
        @Req() request: Request,
    ): Promise<void> {
        // DB에서 해당 직원 연차 기록을 가져온다.
        const annualLeaveRecords = await this.annualLeaveService.showMyAllAcceptAnnualLeave(userId);

        const user: { _id: number; role: string } = request.user as User; // User에서 필요한 것만 빼옴

        if (user._id !== userId) {
            throw new UnauthorizedException('내가 작성한 연차 기록만 받을 수 있습니다.');
        }

        // printService에 있는 엑셀 파일 다운로드를 불러오고 annualLeave를 넣어준다.
        const excelFile = await this.printService.generateExcel(annualLeaveRecords, response);

        return excelFile;
    }
profile
개발 경험치 쌓는 곳

0개의 댓글