Jekson
Jekson

Reputation: 3262

How to protect a column in excel against changes using openpyxl?

I'd like to lock out some of the columns in the for changes. To do that, I first locked out the entire file.

ws = wb["RFI"]
ws.protection.sheet = True

But then I try lock some of columns

for col in ['U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD']:
    ws[col].protection = Protection(locked=False)

I got

AttributeError: 'tuple' object has no attribute 'protection'

Upvotes: 0

Views: 2830

Answers (1)

Dror Av.
Dror Av.

Reputation: 1214

When you are using worksheet['<some letter>'] what you get back is a tuple of all the cells in that column:

ws['A'] -> (Cell A1, Cell A2 ... Cell A<max_row>)

After you lock the sheet you need to iterate over the cells that you want to unlock:

ws = wb["RFI"]
ws.protection.sheet = True

for col in ['U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD']:
        for cell in ws[col]:
            cell.protection = Protection(locked=False)

This way your sheet will be locked but those specific columns will not be.

Upvotes: 2

Related Questions