본문 바로가기
Python/openpyxl

파이썬 openpyxl ValueError: Sheet or range is protected and cannot be modified오류 해결하기

by PySun 2024. 4. 10.
반응형

문제 개요

파이썬에서 openpyxl을 사용하여 엑셀 파일을 수정하려고 할 때 'ValueError: Sheet or range is protected and cannot be modified' 에러가 발생하는 경우가 있습니다. 이 오류는 시트 또는 범위가 보호되어 수정할 수 없을 때 발생하며, 보호된 엑셀 시트에서 데이터를 변경하려고 시도할 때 주로 발생합니다. 이 문제를 해결하기 위한 몇 가지 해결책을 살펴보고, 예시 코드를 통해 안내하겠습니다.

에러 발생 예시 코드

'ValueError: Sheet or range is protected and cannot be modified' 에러가 발생할 만한 간단한 예시 코드를 살펴봅시다.

from openpyxl import Workbook

# 엑셀 워크북 생성
workbook = Workbook()
sheet = workbook.active

# 시트 보호 설정
sheet.protection.set_password("password")
sheet.protection.enable()

try:
    # 보호된 시트에서 데이터 수정 시도
    sheet["A1"] = "New Data"
except ValueError as e:
    print(f"에러 발생: {e}")

에러 해결 방법

1. 시트 보호 해제

보호된 시트에서 데이터를 수정하려면 먼저 시트의 보호를 해제해야 합니다. 아래는 시트 보호를 해제하는 예시 코드입니다.

from openpyxl import Workbook

# 엑셀 워크북 생성
workbook = Workbook()
sheet = workbook.active

# 시트 보호 설정
sheet.protection.set_password("password")
sheet.protection.enable()

# 시트 보호 해제
sheet.protection.disable()

마무리

'ValueError: Sheet or range is protected and cannot be modified' 에러에 대한 해결 방법을 살펴보았습니다. 보호된 시트에서 데이터를 수정하려면 먼저 시트의 보호를 해제해야 합니다.

반응형