01.Computer/Nodejs

{ NodeJs } Elasticsearch + Excel 연동 #1

천랑랑 2020. 11. 19. 13:11

 전제 조건 

elasticsearch에 저장되어있는 값을 가져와서 excel로 출력하려고 합니다.

혹시 elasticsearch에 값을 어떻게 저장해야하는지 모르시다면 아래의 링크를 통해 확인하신 뒤 하시면

도움이 될것이라 생각됩니다.

2020/10/06 - [01.Computer/ELK] - 05.수집(logstash + mysql)

 

05.수집(logstash + mysql)

이 편은 단순히 mysql -> elsticsearch 데이터를 넣는걸을 다룰 것이고, 심화 과정은 차후에 다루고자 한다. 자아아아~~~~!! ElasticSearch 와 Kibana가 정상적으로 시작을 하였다면 데이터를 수집해보자!! 필

2015pyw.tistory.com

자 그럼 만들로 gogogogo~~

 

 첫번째, 설정파일 만들기 

config/index.js => config 폴더를 만들어서 그 하위에 파일을 만들어주도록 합니다. elasticsearch 접속정보 와 2편에 다룰 스케쥴정보에 대해서 작성해주도록 하겠습니다.

module.exports = {
    elasticsearch: {
        hosts: [ 'elastic:123456@localhost:9200' ],
        timeout: 10 * 1000
    },
    settings: {
        schedule: '*/1 * * * *'
    }    
};

 

 

두번째, elasticsearch 모듈 

엘라스틱 관련 모듈도 폴더와 파일을 분리해서 만들어주도록 합니다. 예) esclient\index.js

 

let config = require('../config');

let elasticsearch = require('elasticsearch');

module.exports = new elasticsearch.Client({
    hosts: config.elasticsearch.hosts,
    requestTimeout: config.elasticsearch.timeout
});

 

 

 세번째, Excel File 처리로직 

excel4node를 이용해서 데이터를 출력해보도록 하겠습니다. 해당 라이브러리에 대해서는 아래의 주소를 Click.

www.npmjs.com/package/excel4node

 

excel4node

Library to create Formatted Excel Files.

www.npmjs.com

큰 로직은 별거 없어요. 데이터 불러오기-> 파싱 -> 출력

여기서 특징은 setTimeout을 이용해서 불러온 부분인데 함수를 비동기방식으로 처리를 하기 위해서 사용하는 겁니다.

혹시 개념이 없으시면 관련글 찾아보시면 될 것 같아요.

const esclient = require('../esclient/index');
const excel = require('excel4node');

let params = {
    index: "test*",
    body: {
        query: {
            match_all: {}
        }
    }
};

 

esclient.search(params, function (err, resp) {
    if (err) {
        console.error('getDataError : ' + err);
        return;
    } else {

        let total = resp.hits.total.value;
        if (total > 0) {
            // Create a new instance of a Workbook class
            const workbook = new excel.Workbook();
            setTimeout(setSheet, 1000, workbook, resp.hits.hits);
        }
    }
});


function setSheet(wb, jsonData) {
    // Add Worksheets to the workbook
    let worksheet = wb.addWorksheet('Sheet 1');
    // let worksheet2 = wb.addWorksheet('Sheet 2');
    let titleStyle = setStyle(wb, 'title');
    let contentStyle = setStyle(wb, 'contents');
    let col = 1;
    let rowKeys = Object.keys(jsonData[0]._source);
    for (let idx in rowKeys) {
        var width = 10;
        switch (rowKeys[idx]) {
            case 'dept_name' :
                width = 17;
                break;
            case 'dept_no' :
                width = 40;
                break;
        }
        worksheet.column(col).setWidth(width);
        worksheet.cell(1, col++).string(rowKeys[idx]).style(titleStyle);
    }

    let row = 2;

    for (let idx in jsonData) {
        let source = jsonData[idx]._source;
        let col = 1;
        for (let key in rowKeys) {
            setInputText(worksheet, row, col, source[rowKeys[key]], contentStyle);
            col++;
        }
        row++;
    }
    wb.write('Excel.xlsx');
}


function setStyle(wb, type) {
    let border = {top: {style: 'thin'}, bottom: {style: 'thin'}, left: {style: 'thin'}, right: {style: 'thin'}};
    let alignment = {horizontal: 'center'};
    let family = 'decorative';
    let fillType = 'none';
    let font = {};
    let fill = {};
	// 컬럼별로 스타일을 다르게 표시하고싶으면 아래에 분기를 태워준다
    if (type == 'dept_name') {
        font = {
            bold: true,
            size: 10

        };
        alignment = {horizontal: 'center'};
        fill = {
            patternType: 'solid',
            fgColor: '#F8F5EE'
        };
        fillType = 'pattern';
    }  

    font.family = family;
    fill.type = fillType;
    return wb.createStyle({
        border: border,
        font: font,
        alignment: alignment,
        fill: fill
    });
}

function setInputText(sheet, row, col, text, style) {
    sheet.cell(row, col).style(style);
    if (!text || text === '' || typeof text == 'undefined' || text === undefined || text === 'undefined') {
        return sheet.cell(row, col).string(' ');
    } else {
        text = text.toString().replace(/[\x00-\x09\x0B-\x1F]/gi, '');
        sheet.cell(row, col).string(text);
    }
}

 

 최종결과물 

 

엑셀파일이 생성될 것이고 아래와 같이 출력이 됩니다.

'01.Computer > Nodejs' 카테고리의 다른 글

{ NodeJs } Elasticsearch + Excel + node-cron 응용편 #2  (0) 2020.11.19