Node.js

[node.js/javascript] s3 excel파일 다운로드 받고 excel to json

a-몬드 2022. 11. 21. 08:48
반응형
const XLSX                        = require("xlsx")                                     ;


function excelToJson (excelFile){
      const sheetName = excelFile["SheetNames"][0];
      const sheetData = excelFile["Sheets"][sheetName];
      const keysList = Object.keys(sheetData);
      const data = [];
      let contentKey = []
      let contentList = []; // 목차 list
      let temp = {};
      let before = 2;
      for (let i=0 ; i < keysList.length; i++){
        if (keysList[i].indexOf("!")){
          const regex = /[^0-9]/g; // 숫자 추출하기 위한 정규식
          const keyNumber = parseInt(keysList[i].replace(regex,''));
          const keyStr = keysList[i].replace(keyNumber.toString(), '');
          if (keyNumber === 1){
            contentKey.push(keyStr);
            // 목록만들기
            contentList.push(sheetData[keysList[i]]["v"]);
          }else if (before !== keyNumber ){
            before = keyNumber;
            // 줄바꿈 생김
            data.push(temp);
            temp = {};
            temp[contentList[contentKey.indexOf(keyStr)]] = sheetData[keysList[i]]["v"];
          }else {
            temp[contentList[contentKey.indexOf(keyStr)]] = sheetData[keysList[i]]["v"];
          }
        }
      }
      data.push(temp);
      data.unshift({"contentList" : contentList});
      return data
    }

const {excel} = await s3.getObject(downloadParam).promise();
const oExcel = XLSX.read(excel);

const excelToJsonFile = await excelToJson(oExcel);
# Excel -> json 변환 확인 
console.log(excelToJsonFile);
반응형