在保护工作表时,如何禁用“选择锁定单元格”?
我正在使用xlwings这个工具,想要保护一个工作表,并且不让别人选择被锁定的单元格。我尝试了很多方法,比如设置“AllowSelectingLockedCells=False”、“SelectingLockedCells=False”等等,但在Python控制台上收到了一个错误信息:“TypeError: _Worksheet.Protect() got an unexpected keyword argument 'AllowSelectingLockedcells'”。请问有没有办法可以保护工作表,并且禁用“选择被锁定的单元格”?
import xlwings as xw
folder = "C:\\Python\\DF\\"
xls = "65982.xlsx"
book = xw.Book(folder + xls)
book.app.visible = True
sht = book.sheets["Sheet1"]
sht.api.Protect(DrawingObjects=False, Contents=True, Scenarios=True,
UserInterfaceOnly=False, AllowFormattingCells=False, AllowFormattingColumns=False,
AllowFormattingRows=False, AllowInsertingColumns=False, AllowInsertingRows=False,
AllowInsertingHyperlinks=False, AllowDeletingColumns=False, AllowDeletingRows=False,
AllowSorting=False, AllowFiltering=False, AllowUsingPivotTables=False)
book.save()
1 个回答
1
正如@Siddharth Rout在评论中提到的,这些是由EnableSelection
来控制的。
在下面的代码中,我先取消了对单元格'A1'的锁定,然后应用了EnableSelection
的三种选项之一;
xlNoSelection
意味着当保护开启时,我无法选择任何单元格。
xlNoRestrictions
意味着当保护开启时,我可以选择任何我想要的单元格。
xlUnlockedCells
意味着当保护开启时,我只能选择未锁定的单元格。也就是说,我可以选择工作表上的'A1',但不能选择其他单元格。
import xlwings as xw
from xlwings.constants import EnableSelection
excel_file = 'test.xlsx'
with xw.App(visible=True) as app:
wb = xw.Book(excel_file)
ws = wb.sheets['Sheet1']
ws.range('A1').api.Locked = False
"""
Enable one of the following to set the specified requirement
"""
### Not able to select any cells ###
ws.api.EnableSelection = EnableSelection.xlNoSelection
### Select any cell ###
# ws.api.EnableSelection = EnableSelection.xlNoRestrictions
### Select unlocked cells only ###
# ws.api.EnableSelection = EnableSelection.xlUnlockedCells
ws.api.Protect(Password='test')
wb.save()