Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python xlwt - making a column readonly (cell protect)

Is there a way to make a particular cell read-only/write protected in python xlwt?

I know there's is a cell_overwrite_ok flag which does not allow to overwrite contents of cells (all cells) but can this be done on cell by cell basis.

Thanks, Sun

like image 824
Sunyl Avatar asked Dec 15 '11 20:12

Sunyl


People also ask

How do you make a cell Uneditable in Excel?

Select the column you want to protect, right Click->Format Cells->Protection, select the "Locked" check box. Review tab->Protect Sheet, select the "Protect worksheet and contents of locked cells" check box and protect the sheet using a password.


1 Answers

Excel cells have a locked attribute that is enabled by default. However, this attribute is only invoked when the worksheet's protection attribute is also set to True. If the worksheet is not protected, the locked attribute is ignored.

Therefore, your question isn't best framed as how to make cells read-only. 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)

# ...

The cell styles (easyxf class) are also useful for declaring background color, font weight, etc.

Cheers.

like image 55
pztrick Avatar answered Sep 30 '22 17:09

pztrick