简体   繁体   English

工作簿中受保护的单元格禁用 MS-Excel (openpyxl) 上的格式化工具

[英]Protected cells in Workbook disables formatting tools on MS-Excel (openpyxl)

For my usecase I only want to protect some columns and therefore be able to use formatting and changing values of cells on unprotected columns only.对于我的用例,我只想保护某些列,因此只能在未受保护的列上使用单元格的格式和更改值。 To load my workbook, I use openpyxl.为了加载我的工作簿,我使用 openpyxl。 My code looks as follows:我的代码如下所示:

wb = load_workbook('FILE_NAME.xlsx')
ws = wb['RELEASE_SHEET']
ws.protection.sheet = True

for col in ["A", "B", "C", "D", "E", "F", "G", "H", "I"]:
    for cell in ws[col]:
        cell.protection = Protection(locked=True)

This works perfectly fine and protects every cell in the columns A to I from formatting and changings.这工作得很好,并保护列 A 到 I 中的每个单元格免受格式化和更改。

Opening the excel-file on MS-Office, I can only change the values in the unprotected cells, which is good.在 MS-Office 上打开 excel 文件,我只能更改未受保护单元格中的值,这很好。 However, I can not use any tools at all.但是,我根本无法使用任何工具。 Not even on non-protected cells to format them.甚至在未受保护的单元格上也无法对其进行格式化。 The toolbar seems to be disabled and the worksheet does not react to format-shortcuts.工具栏似乎被禁用,工作表对格式快捷方式没有反应。

在此处输入图像描述

If I unprotect the Sheet it works again.如果我取消保护工作表,它会再次工作。

Do I need to load or save the sheet on another way?我是否需要以其他方式加载或保存工作表? Or is there something wrong with the way I am protecting the cells?还是我保护细胞的方式有问题?

So I found out that you need to set it manually:所以我发现你需要手动设置它:

Simply use只需使用

wb = load_workbook('FILE_NAME.xlsx')
ws = wb['RELEASE_SHEET']
ws.protection.sheet = True
ws.protection.formatCells = False 

formatCells set to false will enable the toolbar again. formatCells 设置为 false 将再次启用工具栏。

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

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