얼음꽃의 일지

[JS] multer, xlsx를 이용한 엑셀파일 데이터 읽기 본문

잡다한 지식

[JS] multer, xlsx를 이용한 엑셀파일 데이터 읽기

얼음꽃 2024. 1. 22. 12:14
728x90

* 엑셀파일은 xlsx 형식 이어야 합니다.

* multer를 이용하는건 스토리지에 저장이 아닌 임시로 넣어두고 불러오기 입니다.

 

1. 설치

-> npm install express multer xlsx

 

2. 코드 작성

const express = require('express');
const multer = require('multer');
const xlsx = require('xlsx');
const app = express();
const port = 3000;

// 파일을 메모리에 저장하는 storage 설정
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// 라우트 컨트롤러 설정
const readExcelController = (req, res) => {
  try {
    // 업로드된 파일은 req.file에 저장됨
    const uploadedFile = req.file;

    // 엑셀 파일을 읽어옴
    const workbook = xlsx.read(uploadedFile.buffer, { type: 'buffer' });

    // 첫 번째 시트 선택
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];

    // 시트의 데이터를 JSON으로 변환
    const jsonData = xlsx.utils.sheet_to_json(sheet);

    // JSON 데이터 반환
    res.json(jsonData);
  } catch (error) {
    console.error(error);
    res.status(500).send('Error processing the file.');
  }
};

// 파일 업로드 및 읽기를 처리하는 엔드포인트
app.post('/readExcel', upload.single('file'), readExcelController);

// 서버 시작
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

 

[추가내용]

 

- post하는 부분에서 upload.single 부분에는 file 을 넣는걸 추천합니다. 다른 값으로 변경해서 하면 인식이 안되더라구여.

- postman에서 작업할시에는 Body -> form-data -> Key : file / 형식도 text가 아닌 file을 하는 것을 추천합니다.

- s3 등 저장하는 방법도 있지만, 일시적으로 읽어와서 데이터만 쓰고 신경 안쓸거기 때문에 memoryStorage에 사용합니다.

 

 

따라서, 데이터가 엄청나게 쌓이지 않으니 크게 신경 안쓰셔도 됩니다.

728x90