简体   繁体   中英

Protected cells in Workbook disables formatting tools on MS-Excel (openpyxl)

For my usecase I only want to protect some columns and therefore be able to use formatting and changing values of cells on unprotected columns only. To load my workbook, I use openpyxl. My code looks as follows:

wb = load_workbook('FILE_NAME.xlsx')
ws = wb['RELEASE_SHEET']
ws.protection.sheet = True

for col in ["A", "B", "C", "D", "E", "F", "G", "H", "I"]:
    for cell in ws[col]:
        cell.protection = Protection(locked=True)

This works perfectly fine and protects every cell in the columns A to I from formatting and changings.

Opening the excel-file on MS-Office, I can only change the values in the unprotected cells, which is good. However, I can not use any tools at all. Not even on non-protected cells to format them. The toolbar seems to be disabled and the worksheet does not react to format-shortcuts.

在此处输入图像描述

If I unprotect the Sheet it works again.

Do I need to load or save the sheet on another way? Or is there something wrong with the way I am protecting the cells?

So I found out that you need to set it manually:

Simply use

wb = load_workbook('FILE_NAME.xlsx')
ws = wb['RELEASE_SHEET']
ws.protection.sheet = True
ws.protection.formatCells = False 

formatCells set to false will enable the toolbar again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM