XlsxWriter: lock only specific cells

I am creating xlsx files with xlsxwriter and want to protect specific cells (for example, all cells in the range B2: B20). The documentation says that you can use the worksheet.protect() method - it enables protection for the entire worksheet by default, and then you can use workbook.add_format({'locked': 0}) to unlock certain cells. But I want the other way around: I want to block only a certain range of cells and leave the rest of the worksheet unlocked. How can i do this?

+5
source share
1 answer

The way to do this is the same as in Excel: set the unlock format for the whole sheet .

In Excel and XlsxWriter, this means setting the unlock format for all columns. Like this:

 import xlsxwriter workbook = xlsxwriter.Workbook('protection.xlsx') worksheet = workbook.add_worksheet() # Create some cell formats with protection properties. unlocked = workbook.add_format({'locked': False}) locked = workbook.add_format({'locked': True}) # Format the worksheet to unlock all cells. worksheet.set_column('A:XDF', None, unlocked) # Turn worksheet protection on. worksheet.protect() # Write a locked and an unlocked cell. worksheet.write('B1', 'Cell A1 is locked. It cannot be edited.') worksheet.write('B2', 'Cell A2 is unlocked. It can be edited.') worksheet.write('B3', 'Cell A3 is unlocked. It can be edited.') worksheet.write('A1', 'Hello', locked ) worksheet.write('A2', 'Hello', unlocked) worksheet.write('A3', 'Hello' ) # Unlocked by default. workbook.close() 
+6
source

Source: https://habr.com/ru/post/1260575/


All Articles