简体   繁体   English

在python openpyxl中锁定一些单元格进行编辑

[英]Lock some cells from editing in python openpyxl

I'm using openpyxl to work with Microsoft Excel files (.xlsx/.xlsm), however I am struggling to lock cells (ie. prevent editing). 我正在使用openpyxl来处理Microsoft Excel文件(.xlsx / .xlsm),但我正在努力锁定单元格(即阻止编辑)。 My current code is this: 我目前的代码是这样的:

lock = Protection(locked=True,
                    hidden=False)
ws['A1'].protection = lock  # ws is my worksheet

However, I am still able to edit cell A1 . 但是,我仍然可以编辑单元格A1 How can I fix it? 我该如何解决?

Edit: 编辑:

This link (to a openpyxl email chain) recommends locking the entire sheet and then to unlock all of the cells but for A1 . 链接 (指向openpyxl电子邮件链)建议锁定整个工作表,然后解锁所有单元格,但对于A1 However, this does not look like a reliable solution as I'll be dumping large amounts of data. 但是,这看起来不像是一个可靠的解决方案,因为我将转储大量数据。

Lock the entire sheet: 锁定整张纸:

    ws.protection.sheet = True

Then unlock the cells that can be edited 然后解锁可编辑的单元格

     cell.protection = Protection(locked=False)

You also need to set protection for the whole worksheet. 您还需要为整个工作表设置保护。 The specification says this about protection for individual cells: 规范说明了关于单个细胞的保护:

A boolean value indicating if the cell is locked. 一个布尔值,指示单元格是否已锁定。 When cells are marked as "locked" and the sheet is protected, then the options specified in the Sheet Part's sheetProtection element (§18.3.1.85) are prohibited for these cells. 当单元格被标记为“已锁定”且工作表受到保护时,这些单元格将禁止在Sheet Part的sheetProtection元素(第18.3.1.85节)中指定的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM