728x90
반응형
1. 엑셀 파일 내용 수정
- 엑셀 파일의 내용을 수정할 때는 원본 파일에서 직접 수정하는 것이 아니라, 원본 엑셀 파일을 읽고 workbook을 만든 후
workbook 내용을 수정하고 새로운 엑셀 파일을 생성하는 방식으로 한다.
const xlsx = require('xlsx');
const workbook = xlsx.readFile('./xlsx/test.xlsx'); // 액샐 파일 읽어오기
const firstSheetName = workbook.SheetNames[0]; // 첫 번째 시트 이름 가져오기
const firstSheet = workbook.Sheets[firstSheetName]; // 시트 이름을 이용해 엑셀 파일의 첫 번째 시트 가져오기
firstSheet['B2'].v = 'test@gmail.com'; // 셀 오브젝트의 키에 값을 할당해 이메일 주소 변경
firstSheet['A3'] = {t:'S', v: 'Lee'}; // 셀을 정의한 자바스크립트 오브젝트를 셀에 할당해서 새로운 셀 추가
xlsx.writeFile(workbook, './xlsx/test2.xlsx');
2. 클라이언트에서 업로드한 엑셀 파일 읽기
- xlsx_upload.html 파일 생성 후 HTML 코드 작성
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<form
action="http://localhost:3000/upload/customers"
method="post"
enctype="multipart/form-data"
>
<input type="file" name="xlsx" accept=".xlsx" />
<input type="submit" value="업로드" />
</form>
</body>
</html>
- xlsx_upload.js 파일을 생성하고 코드를 작성
const multer = require('multer');
const path = require('path');
const xlsx = require('xlsx');
require('dotenv').config({ path: 'mysql/.env' }); // mysql 폴더에 있는 .env 파일을 찾아서 환경변수를 설정
const mysql = require("./mysql"); // mysql 폴더의 index.js
const express = require('express');
const app = express();
app.use(express.json({
limit: '50mb' // 최대 50메가
})); // 클라이언트 요청 body를 json으로 파싱 처리
app.listen(3000, () => {
// 3000번 포트로 웹 서버 실행
console.log('Server started. port 3000.');
});
const storage = multer.diskStorage({ // 디스크 저장소 정의
destination: function (req, file, cb) {
cb(null, 'uploads/') // cb 콜백함수를 통해 전송된 파일 저장 디렉토리 설정
},
filename: function (req, file, cb) {
// cb(null, file.originalname) // cb 콜백함수를 통해 전송된 파일 이름 설정
cb(null, new Date().valueOf() + path.extname(file.originalname)); //시스템시간으로 파일 이름 설정
}
})
const upload = multer({ storage: storage }); // multer 객체 생성
app.post('/upload/customers', upload.single('xlsx'), function (req, res, next) {
const workbook = xlsx.readFile(`./uploads/${req.file.filename}`); // 엑셀 파일 읽어오기
const firstSheetName = workbook.SheetNames[0]; // 엑셀 파일의 첫번째 시트 이름 가져오기
const firstSheet = workbook.Sheets[firstSheetName]; // 시트 이름을 사용해서 엑셀 파일의 첫번째 시트 가져오기
const firstSheetJson = xlsx.utils.sheet_to_json(firstSheet); // utils.sheet_to_json 함수를 사용해서 첫번째 시트 내용을 json 데이터로 변환
firstSheetJson.forEach(async (customer) => {
await mysql.query('customerInsert', customer); // 고객 정보 데이터를 한건씩 읽으면서 MySQL 데이터베이스에 insert 처리
})
res.send('ok');
});
- 업로드를 위한 엑셀 파일 생성
- xlsx_upload.html을 Live Server로 실행 파일 업로드
728x90
반응형
'Runtime > Node.js' 카테고리의 다른 글
28. 웹소켓 (1) | 2023.04.30 |
---|---|
27. 엑셀 파일 처리(엑셀 파일 생성) (4) | 2023.04.26 |
25. 엑셀 파일 처리(엑셀 파일 읽기) (4) | 2023.04.24 |
24. 작업 스케줄러(Job Scheduler) (3) | 2023.04.23 |
23. 메일링 서비스(mailtrap 서비스) (2) | 2023.04.19 |