В файле Excel я хочу защитить все ячейки, содержащие формулы.
Итак, я сначала разблокирую все ячейки, а затем блокирую только те ячейки, в которых есть формула.
Когда я защищаю лист паролем, я также передаю все соответствующие свойства защиты, такие как:
AllowFormattingCells,
AllowFormattingColumns,
AllowFormattingRows,
AllowInsertingColumns,
AllowInsertingRows,
AllowSorting и
AllowFiltering
и установите для них значение True. Однако, если я проверю свойства после защиты листа, они вернутся как False.
Когда я открываю файл с помощью Excel, лист защищен, и я могу редактирую содержимое разблокированных ячеек, но не могу форматировать, фильтровать, вставлять столбцы или строки или делать что-либо еще.
Соответствующая информация
- Версия Python: 3.11.9
- Версия pywin32: 306
- Версия Excel: Microsoft® Excel® для Microsoft 365 MSO (версия 2402, сборка 16.0.17328.20550) 64- бит
- Windows: Edition Windows 11 Enterprise
- Версия 23H2
- Установлено 18-10-2023 г.
- Сборка ОС 22631.4317
- Используйте функции Windows Пакет опыта 1000.22700.1041.0
Код: Выделить всё
import win32com.client
excel_app = win32com.client.DispatchEx("Excel.Application")
excel_app.Visible = False
workbook = excel_app.Workbooks.Open("path_to_file.xlsx")
sheet = workbook.Sheets("Sheet1")
all_cells = sheet.Cells
merge_cells = sheet.Cells(1, 1).MergeArea
edited_cell = merge_cells.Cells(1, 1)
value = edited_cell.Formula if edited_cell.HasFormula else edited_cell.Value
edited_cell.Formula = "=1+1"
formula_cells = all_cells.SpecialCells(Type=-4123) # -4213 represent xlCellTypeFormulas
all_cells.Locked = False
formula_cells.Locked = True
if isinstance(value, str) and value.startswith("="):
edited_cell.Formula = value
else:
edited_cell.Value = value
merge_cells.Locked = False
sheet.Protect(
Password="random_password",
Contents=True,
UserInterfaceOnly=True,
AllowFormattingCells=True,
AllowFormattingColumns=True,
AllowFormattingRows=True,
AllowInsertingColumns=True,
AllowInsertingRows=True,
AllowSorting=True,
AllowFiltering=True,
)
print("AllowFormattingCells: ", sheet.Protection.AllowFormattingCells)
print("AllowFormattingColumns: ", sheet.Protection.AllowFormattingColumns)
print("AllowFormattingRows: ", sheet.Protection.AllowFormattingRows)
print("AllowInsertingColumns: ", sheet.Protection.AllowInsertingColumns)
print("AllowInsertingRows: ", sheet.Protection.AllowInsertingRows)
print("AllowSorting: ", sheet.Protection.AllowSorting)
print("AllowFiltering: ", sheet.Protection.AllowFiltering)
workbook.Save()
excel_app.Quit()
Я пробовал все комбинации для «Содержимое» и «UserInterfaceOnly», чтобы увидеть, может ли это привести к его изменению.
Подробнее здесь: https://stackoverflow.com/questions/791 ... ng-pywin32
Мобильная версия