Python 使用Win32Com 创建Excel对象直接操作Excel

import win32com.client

xl= win32com.client.Dispatch("Excel.Application")

wb=xl.Workbooks.open(r'C:\Users\ming12.liu\Desktop\Book1.xlsx')

sheet=wb.worksheets(1)

sheet.Protection.AllowEditRanges.Add("Ops", sheet.Columns("B"), "Ops")

sheet.Protect(Password:="F&C", DrawingObjects:=True, Contents:=True, Scenarios:=True)

wb.Save()

wb.Close()

xl.Application.Quit()

其中遇到一个问题,当sheet已经被保护了,再次执行代码时报错:

Traceback (most recent call last):

File "c:\Users\ming12.liu\Desktop\import win32com.py", line 8, in <module>

sheet.Protection.AllowEditRanges.Add("Ops", sheet.Columns("B:B"))

pywintypes.com_error: (-2147352567, '发生意外。', (0, None, None, None, 0, -2146827284), None)

相关推荐
BD_Marathon3 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw3 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Resean02233 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
Wellijohn4 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
学长毕设4 小时前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
Logintern096 小时前
deep agents 多智能体模式——规划与委派
python·langchain
Flynt6 小时前
Spring AI Alibaba 真停更了?我把它的 GitHub 翻了个底朝天
java·spring·开源
2601_967980118 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
她的男孩9 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
databook10 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析