[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

 

반응형

[NestJS] read excel file With exceljs (DiskStorage)

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

NestJS 에서는 파일 업로드시 메모리에서 읽는 방식(MemoryStorage)
과 디스크에서 읽는 방식(DiskStorage) 으로 구성되어 있다.

 

아래 방법은 DiskStorage 를 사용했을때, 해당 경로에 있는 Excel 파일을 읽어서 출력해주는 방법이다.

 

1. npm 설치

npm install exceljs

 

 

2. 많은 예제를 참고하여   DiskStorage 으로 구성되어 있을 경우  file.path 를 이용하여 파일 경로를 읽어서 엑셀 파일 내용을 읽어 온다.

import { Cell, Row, Workbook } from 'exceljs';

...

  // 엑셀 업로드
  @Post('uploadExcel')
  @UseInterceptors(FileInterceptor('file'))
  async uploadExcel(
      @UploadedFile() file : Multer.file) {
    
    ...
    
      var workbook = new Workbook();
      await workbook.xlsx.readFile(file.path);
      var sheet = workbook.worksheets[0];

      // 1 ~ N ROW
      var rows : Row[] = sheet.getRows(1, sheet.rowCount);
      var cell : Cell;

      rows.forEach(row => {

        // 1 ~ N Cell
        row.eachCell((cell: Cell, colNumber: number)=>{

          Logger.debug("colNumber, cell value ", cell.value, colNumber);

        })

      });
  
  ....
 }

 

반응형

[NestJS] Image file download with Url

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

 

1. npn install

npm i --save @nestjs/axios axios

 

 

2.Model 에 HttpModule 추가

  import { HttpModule } from '@nestjs/axios';
  
  @Module({
 
  imports: [
    HttpModule
  ]

 

 

3. 다운로드를 구현할 Service 에서 아래 코드를 추가하여 다운로드

import { HttpService } from '@nestjs/axios';

@Injectable()
export class ApiService {
  constructor(
    , private readonly httpService : HttpService

...
..
async downLoadImage() {

    const writer = fs.createWriteStream('저장할 파일 경로');

    const response = await this.httpService.axiosRef({
        url: 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
        method: 'GET',
        responseType: 'stream',
    });

    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
        writer.on('finish', resolve);
        writer.on('error', reject);
    });
    
    }
반응형