엄지월드

node를 이용한 excel 파일 생성 예제 본문

Node.js

node를 이용한 excel 파일 생성 예제

킨글 2019. 9. 12. 20:34
반응형

DB에 저장되어 있는 값을 excel로 다운로드하고 싶다는 요청이 들어왔다.

그래서 특정 url 접근 시, excel로 데이터를 다운로드 받는 기능을 추가하였다.

(밑에 예제는 DB 관련 내용은 제외하였다)

 

* excel4node라는 library를 설치해줘야 정상 작동한다.

router.get('/', function(req, res, next) {
    var xl = require('excel4node'); // npm install excel4node --save 를 통해 설치

    // Create a new instance of a Workbook class
    var wb = new xl.Workbook();

    // Add Worksheets to the workbook
    var ws = wb.addWorksheet('Sheet 1');
    var ws2 = wb.addWorksheet('Sheet 2');

    // Create a reusable style
    var style = wb.createStyle({
      font: {
        color: '#FF0800',
        size: 12,
      }
      // ,numberFormat: '$#,##0.00; ($#,##0.00); -',
    });
    
    // Set value of cell A1 to 100 as a number type styled with paramaters of style
    ws.cell(1, 1)
      .string('text')
      .style(style);
    ws.cell(1, 2)
      .number(100)
      .style(style);

    // Set value of cell B1 to 200 as a number type styled with paramaters of style
    ws.cell(1, 3)
      .date(new Date())
      .style(style);

    // Set value of cell C1 to a formula styled with paramaters of style
    ws.cell(1, 4)
      .formula('A1 + B1')
      .style(style);

    // Set value of cell A2 to 'string' styled with paramaters of style
    ws.cell(1, 5)
      .string('id')
      .style(style);

    // Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
    ws.cell(1, 6)
      .bool(true)
      .style(style)
      .style({font: {size: 14}});
      
    wb.write('Excel.xlsx', res); // download

});

참고 :  https://www.npmjs.com/package/excel4node

 

 

도움이 되셨다면 광고 한번씩 클릭 부탁드립니다 😁

 

 

'Node.js' 카테고리의 다른 글

node ERR_UNESCAPED_CHARACTERS('Request path');  (0) 2021.02.27
node 다른 파일 코드 참조  (0) 2020.01.19
node를 이용한 API 호출 시 body 값 설정 방법  (0) 2019.09.07
ejs 활용 json 읽기  (0) 2019.09.04
node Session 구현  (0) 2019.06.28
Comments