在保护工作表时,我想禁用“选择锁定的单元格”

问题描述 投票:0回答:1

我正在使用 xlwings,我想通过取消选中“选择锁定单元格”来保护工作表。我尝试了很多尝试,例如“AllowSelectingLockedCellls = False”、“SelectingLockedCells = False”等,并且我从Python控制台收到一条消息“TypeError:_Worksheet.Protect()得到了意外的关键字参数'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()
python excel xlwings
1个回答
0
投票

正如 @Siddharth Rou 在他的评论中所说,这些由

EnableSelection
控制。

在以下代码中,我删除了单元格“A1”上的锁定,然后应用 EnableSelection 的 3 个选项之一;

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

    ws.api.Protect(Password='test')

    ### 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


    wb.save()
© www.soinside.com 2019 - 2024. All rights reserved.