본문 바로가기
django

Excel data DB insert & the other way

by hyundy 2021. 10. 19.

업무 자동화 프로젝트 진행에 있어 Excel 데이터를 DB에 넣거나 반대로 DB 정보를 조회해서 Excel로 만드는 기능이 필요 했다. 

 

Excel 데이터를 읽어 오는것은 pandas 를 사용 한다. 

import pandas as pd
import warnings
from excel.models import Exceltestdata

# warnigs 메세지 삭제
with warnings.catch_warnings(record=True):
    warnings.simplefilter("always")
    # 엑셀 읽어오는 부분
    df = pd.read_excel(
        "/Users/dayong/project/algorithm/cvstest/cvsdata/급상여.xlsx", engine="openpyxl")
                        
#list 값이 모두 NaN인 데이터 제외
data = df.dropna(how='all')


# 엑셀 데이터 db insert
for dbfram in data.itertuples():
    obj = Exceltestdata.objects.create(
        code=dbfram.CODE,
        name=dbfram.NAME,
        ssnum=dbfram.SSNUM,
        onemonth=dbfram.ONE,
        twomonth=dbfram.TWO,
        thmonth=dbfram.THREE,
    )
    obj.save()

미리 만들어둔 model Exceltestdata class를 호출해 DB에 넣으면 성공

 

 

반대도  알아보자

# db 데이터 엑셀 insert
obj = Exceltestdata.objects.all().values_list()
resultdata = []
for i in obj:
    resultdata.append(i)

result = pd.DataFrame(resultdata)
result.columns = ["NO","코드","사원명","주민번호","1월","2월","3월"]
print(result)

#result.to_excel('../media/result/dbDataExcel.xlsx')

- DB 튜플 정보를 list 형태로 가지고와 DataFrame 으로 만들어 준다.  

- 테이블 컬럼정보(DB attribute)는 가지고 오지 않기 때문에 지정 해줬다.

'django' 카테고리의 다른 글

Django Form, Serializer  (0) 2021.11.23
Add a module and use a model  (0) 2021.10.18
django mysql connection error  (0) 2021.10.14
django file upload & download  (3) 2021.10.12
django 기본 구조  (0) 2021.10.11