In the Excel object model, the ProtectContents property of a Worksheet object is a read-only Boolean property that indicates whether the contents (cells) of a worksheet are currently protected. When a worksheet is protected, users are typically restricted from modifying locked cells, and the ProtectContents property returns True. Conversely, if the worksheet is unprotected, it returns False. This property is useful for programmatically checking the protection status of a worksheet, allowing for conditional logic in automation scripts, such as only performing certain operations if the sheet is unprotected or alerting the user if protection is active.
The ProtectContents property corresponds to the ProtectContents attribute in the Excel object model. In xlwings, you can access this property through the api property of a sheet object, which provides direct access to the underlying Excel object model. The syntax for accessing ProtectContents in xlwings is as follows:
sheet.api.ProtectContents
Here, sheet is an xlwings Sheet object representing the worksheet. The api property exposes the native Excel VBA object model, so ProtectContents is called as a property without any parameters. It returns a Boolean value (True or False). Note that this property is read-only; to change the protection status, you would use methods like Protect or Unprotect on the worksheet object.
For example, to check if the active sheet is protected, you can use the following xlwings code:
import xlwings as xw
# Connect to the active Excel instance and workbook
app = xw.apps.active
wb = app.books.active
sheet = wb.sheets.active
# Check the ProtectContents property
is_protected = sheet.api.ProtectContents
if is_protected:
print("The worksheet is protected. Contents cannot be modified.")
else:
print("The worksheet is unprotected. Contents can be modified.")
In this example, sheet.api.ProtectContents retrieves the protection status, and the script prints a message based on the result. This can be integrated into larger automation tasks, such as ensuring data integrity by preventing modifications on protected sheets or temporarily unprotecting a sheet to perform updates before re-protecting it.
Another practical use case is to loop through all worksheets in a workbook and report their protection status:
import xlwings as xw
# Open a workbook
wb = xw.books.active
for sheet in wb.sheets:
status = "Protected" if sheet.api.ProtectContents else "Unprotected"
print(f"Sheet '{sheet.name}': {status}")
Leave a Reply