대용량 엑셀 파일을 다룰 때는 read_only 및 wrtie_only 모드를 사용하여 메모리 사용량을 줄이고 성능 최적화를 통해 메모리 부족, 실행 속도 저하와 같은 문제들을 해결할 수 있음
- Read only : 읽기 전용으로 파일을 열며, 셀 데이터를 순차적으로 읽기 때문에 메모리 사용량이 적음
- Write only : 쓰기 전용 워크북으로, 셀 데이터를 하나씩 추가할 수 있고 메모리에 전체를 보관하지 않기 때문에 빠르고 가벼움
엑셀 파일 구성
▪ large_file.xlsx : 10,000행 × 10열의 무작위 숫자 데이터가 포함된 대형 엑셀 파일
▪ large_output.xlsx : Write Only로 저장한 10,000행 × 10열 데이터
예제 코드 01 - Read Only
▪ "large_file.xlsx" 읽기 전용으로 열기
▪ iter_rows()를 통해 10 × 3 데이터 출력
from openpyxl import load_workbook
import os
# You must change the physical path before running this script.
currPath = "C:/Users/natio/OneDrive - 성균관대학교/99. Personal Blog/05. Python/05. OPENPYXL/02. Cell Example/13. 읽기-쓰기 성능 최적화/"
wb = load_workbook(filename=currPath+"large_file.xlsx", read_only=True)
ws = wb.active
for row in ws.iter_rows(min_row=1, max_col=3, max_row=10):
print([cell.value for cell in row])
▪ 새 워크북을 통해 코드에서 실행한 10000 × 10 데이터 Excel file로 저장
from openpyxl import Workbook
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_dir, "large_output.xlsx")
wb = Workbook(write_only=True)
ws = wb.create_sheet()
for i in range(1, 10001):
ws.append([i, i * 2, i * 3, i * 4, i * 5, i * 6, i * 7, i * 8, i * 9, i * 10])
wb.save(file_path)
wb.close()
print(f"파일이 저장되었습니다: {file_path}")