본문 바로가기
ETC/Python

[Python] 파이썬 엑셀 읽기, 쓰기 + xlrd not supported error 해결방법

by Guardy 2021. 2. 21.
728x90

xlrd not suported xlrd.biffh.XLRDError xlrd pandas python excel python excel read write 

이번 글에서는 파이썬의 pandas 모듈을 이용해 엑셀 파일을 다루는 법에 대해서 알려드리고자 합니다.

다음과 같은 엑셀 파일이 있다고 가정합니다.

보통 파이썬으로 엑셀을 다룰 때 csv 모듈을 이용해 배열에 넣는것이 제일 쉽겠지만, 위의 경우처럼 이름에 해당하는 열, 나이에 해당하는 열, 성적에 해당하는 열처럼 가로가 아닌 세로형태일때 데이터를 다룰때는 pandas를 사용하는 것이 편리하고 좋은 프로그래밍 방식이 될 수 있습니다.

위 엑셀파일을 py 코드 파일이 있는 폴더에 test.xlsx로 저장해주었습니다.(주의! csv형식이 아닌 xlsx입니다)

다음과 같이 코드를 작성하고 실행시켰는데 오류가 발생합니다.

import pandas as pd

df = pd.read_excel('test.xlsx',sheet_name='Sheet1')
print(df)
$ python test.py
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    df = pd.read_excel('test.xlsx',sheet_name='Sheet1')
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\util\_decorators.py", line 296, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\io\excel\_base.py", line 304, in read_excel
    io = ExcelFile(io, engine=engine)
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\io\excel\_base.py", line 867, in __init__
    self._reader = self._engines[engine](self._io)
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\io\excel\_xlrd.py", line 21, in __init__
    import_optional_dependency("xlrd", extra=err_msg)
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\compat\_optional.py", line 110, in import_optional_dependency
    raise ImportError(msg) from None
ImportError: Missing optional dependency 'xlrd'. Install xlrd >= 1.0.0 for Excel support Use pip or conda to install xlrd.

xlrd가 설치되어있지 않아 발생한 오류입니다. 아래에 설치하라고 친절하게 나와있으니 설치해줍니다.

pip install xlrd

xlrd를 설치해줬더니 다음과 같은 오류가 또 발생합니다.

  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\xlrd\__init__.py", line 170, in open_workbook
    raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported')
xlrd.biffh.XLRDError: Excel xlsx file; not supported

해결방법은 다음과 같습니다. 엔진을 openpyxl을 쓰겠다고 선언해주면됩니다. 코드를 다음과 같이 수정해줍니다.

import pandas as pd

df = pd.read_excel('test.xlsx',sheet_name='Sheet1',engine='openpyxl')
print(df)

안될것만 같았던 코드가 정상적으로 실행되고 결과도 제대로 나옵니다.

만약 이름만 list로 보고 싶다면 다음과 같이 코드를 작성하면 됩니다.

print(df['이름'])

 

도움이 되셨다면 공감과 댓글 부탁드립니다!

728x90