티스토리 뷰

발생일: 2015.12.21

키워드: openpyxl, xlrd, 파이썬 엑셀, python excel, read excel file using python, xlsx

문제:
파이썬으로 엑셀 파일을 읽어오려고 한다.


해결책:

내가 검색을 짧게 해서 그런지 모르겠지만, xls 형식의 파일과 xlsx 형식의 파일을 지원하는 라이브러리는 찾지 못했다.

xls 파일을 읽어오려면 xlrd 라이브러리를,
xlsx 파일을 읽어오려면 openpyl 라이브러리를 사용하면 된다.



먼저, xls 파일은 xlrd 라이브러 사용해서 아래처럼 가져올 수 있다.

workbook = xlrd.open_workbook(file_contents=excel_file.read())
sheet = xl_workbook.sheet_by_index(0)


xlsx 파일은 아래처럼 가져오면 된다.

#workbook = load_workbook(filename=file, read_only=True)
workbook = load_workbook(filename=BytesIO(excel_file.read()), read_only=True)
worksheet = wb.active

for row in worksheet.rows:
    for cell in row:
        print(cell.value)


논의:

처음엔 workbook과 worksheet이 헷갈렸었다.

- workbook: 엑셀 파일 전체라고 보면 된다. (모든 시트를 포함)
- worksheet: (또는 sheet) 엑셀 시트 한 개

반응형
댓글
공지사항