Python xlwt - create readonly column (cell protection)

Is there a way to make a specific read / write cell protected in python xlwt?

I know that there is a flag cell_overwrite_ok, which does not allow overwriting the contents of cells (all cells), but this can be done based on cells by cells.

Thanks sun

+5
source share
1 answer

In Excel cells there is a locked attribute , which is enabled by default. However, this attribute is only called when the worksheet security attribute is also set to True. If the worksheet is not protected, the attribute locked is ignored.

Therefore, your question is not best framed by how to make read-only cells. Rather, the question is how to make cells editable after protecting the worksheet.

... Here you are:

from xlwt import Workbook, Worksheet, easyxf

# ...

# Protect worksheet - all cells will be read-only by default
my_worksheet.protect = True  # defaults to False
my_worksheet.password = "something_difficult_to_guess"

# Create cell styles for both read-only and editable cells
editable = easyxf("protection: cell_locked false;")
read_only = easyxf("")  # "cell_locked true" is default

# Apply your new styles when writing cells
my_worksheet.write(0, 0, "Can't touch this!", read_only)
my_worksheet.write(2, 2, "Erase me :)", editable)

# ...

Cell styles easyxfare also useful for declaring background colors, font weights, etc.

Greetings.

+9
source

All Articles