问题
I'm creating xlsx files with xlsxwriter and want to protect specific cells (for example all cells in a range B2:B20). The documentation says that you can use worksheet.protect()
method - it's turn on protection for whole worksheet by default - and then you can use workbook.add_format({'locked': 0})
for unlocking specific cells. But I want vice versa - I want to lock only specific range of cells and leave the rest of the worksheet unlocked. How can I do this?
回答1:
The way to do this is the same as in Excel: set an unlock format for the entire sheet.
In Excel and XlsxWriter this translates to setting a unlock format for all the 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()
来源:https://stackoverflow.com/questions/40885097/xlsxwriter-lock-only-specific-cells