728x90

엑셀 파일 불러와서 뿌려주기 #1


파일로 저장되어 있는 공공표준용어 데이터를 읽어와서 url로 접속시 해당 내용을 뿌려주는 작업을 진행해보자!!

 

먼저 , 파일을 불러오기 위한 방법으로는 pandas를 사용한다.

진행 순서는 아래와 같다.

 

1. pandas ExcelFile 로 엑셀 파일을 불러와서 sheet 이름들을 가져온다.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelFile.html

 

pandas.ExcelFile — pandas 2.2.1 documentation

A file-like object, xlrd workbook or openpyxl workbook. If a string or path object, expected to be a path to a .xls, .xlsx, .xlsb, .xlsm, .odf, .ods, or .odt file.

pandas.pydata.org

2. 각 시트 별로 read_excel로 데이터 프레임을 만들어 준다.

3. 데이터를 정렬 시키고 새 index를 부여한다.

4. 각 데이터프레임을 api query string에 맞춰 return 시킨다.

5. 최소 출력 row 수는 10개이다.

 

 

1. 파일 불러오기


 

pandas에서 엑셀 파일을 불러오기 위해서는 openpyxl 패키지가 필요합니다.

 

requirements.txt에 추가하고 설치합니다.

 

openpyxl==3.1.2

 

프로젝트 디렉토리에 upload 디렉토리를 만들고 파일을 넣어줍니다.

 

이제 기존에 있던 소스 코드를 지우고 새로 작성해 보겠습니다.

 

pandas를 import 하고 ExcelFile의 인자값으로 파일이 위치한 경로를 절대경로로 넣어줍니다.

 

import pandas as pd

xlsx = pd.ExcelFile("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx")

 

이제 ExcelFile에서는 sheet_names를 통해서 이 엑셀 파일의 sheet들의 이름 정보를 리스트로 가져올 수 있습니다.

if __name__ == "__main__": 을 통해서 print 찍어 보겠습니다.

 

import pandas as pd

xlsx = pd.ExcelFile("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx")



if __name__ == "__main__":
    print(xlsx.sheet_names)
    

 

 

실제 파일과 비교해 보겠습니다.

실제 파일에서 보이는 sheet는 총 3개이지만 sheet_names로 표시되는 element 수는 4개입니다.

엑셀 파일에서 숨기기 취소를 보면 '공통표준도메인 초안 1' 숨기기 처리 된것을 볼 수 있습니다.

 

 

이제 이 파일에 들어있는 시트별로 데이터프레임을 만들어 주고

딕셔너리를 만들어 줍니다.

"""
main.py
@제목: 메인 실행 파일
@설명: 메인 실행 파일

    작성일자        작성자
-----------------------
    2024.03.14    hiio420

"""

import pandas as pd

# 엑셀 파일 불러오기
xlsx = pd.ExcelFile("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx")

# 각 시트 별 DataFrame 생성
df_cmStdTrm = pd.read_excel("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx",sheet_name=xlsx.sheet_names[0])
df_cmStdWd = pd.read_excel("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx",sheet_name=xlsx.sheet_names[1])
df_cmStdDmn = pd.read_excel("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx",sheet_name=xlsx.sheet_names[2])
df_cmStdTmplt = pd.read_excel("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx",sheet_name=xlsx.sheet_names[3])


# DataFrame을 Value로 하고 키가 int인 딕셔너리 생성
df_dict = {
    0:df_cmStdTrm,
    1:df_cmStdWd,
    2:df_cmStdDmn,
    3:df_cmStdTmplt
}



if __name__ == "__main__":

    print(xlsx.sheet_names)
    print([(key,value.size) for key,value in df_dict.items()])

 

 

 

2. Get Routing


이제 df_dict에 있는 데이터를 Routing 하는 함수를 만들어 줍니다.

@app.get("/")
def read_root(id: int = 0):
    data = df_dict[id].to_dict("records")
    return {"sheetName": xlsx.sheet_names[id], "data": data}

아직 API에 대한 정확한 정보를 작성하지는 않았습니다.

 

쿼리 스트링으로 id 값을 받고 기본값으로는 0을 입력합니다.

 

응답으로는 data와 함께 sheet 명을 추가적으로 전달합니다.

 

서버를 실행하고 http://127.0.0.1:4882/ 접속해보면

 

정상적으로 출력 되는 것을 볼 수 있습니다.

 

그럼 query String 을 url에 추가로 입력에 id 값을 1로 하여 보내봅니다.

 

 

서버 에러가 나버렸습니다.

서버 로그를 보면

ValueError: Out of range float values are not JSON compliant 에러가 발생했습니다.

Nan이나 null 값이 Dataframe에 있기때문에 결측치 값 처리를 해줘야 할거 같습니다.

 

Pandas fillna를 이용해 결측치를 모두 빈문자열로 만들어 줍니다.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html

 

pandas.DataFrame.fillna — pandas 2.2.1 documentation

If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is t

pandas.pydata.org

# 각 시트 별 DataFrame 생성
df_cmStdTrm = pd.read_excel("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx",
                            sheet_name=xlsx.sheet_names[0]).fillna("")
df_cmStdWd = pd.read_excel("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx",
                           sheet_name=xlsx.sheet_names[1]).fillna("")
df_cmStdDmn = pd.read_excel("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx",
                            sheet_name=xlsx.sheet_names[2]).fillna("")
df_cmStdTmplt = pd.read_excel("F:\\[01]project\\commonStandardTerm\\upload\\(붙임)공공데이터 공통표준용어(2022.7월).xlsx",
                              sheet_name=xlsx.sheet_names[3]).fillna("")

 

이후 다시 서버를 reload 하고 

 

접속해 봅니다.

 

이제 정상적으로 출력 되는 것을 볼 수 있습니다.

 

 

728x90

+ Recent posts