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)

相关推荐
新*12 小时前
520 万数据迁移实战:Elasticsearch 索引重建与"改名"的完整踩坑记录
python·mysql·elasticsearch·数据迁移
吴名氏.13 小时前
Java转AI Agent教程(第十五周)政策时效:过期政策不该被召回,也不能被删掉
java·人工智能·python·ai·ai agent
文丑颜不良啊1 天前
LeetCode2981~3000题目解析
java·leetcode
黑客笔记1 天前
python小工具win7翻车事故现场
python
nice_lcj5201 天前
【从零理解 Spring AI · 13】RAG 要解决什么:把“闭卷考试“变成“开卷“
java·spring·检索增强·rag·spring ai·ai应用开发
学长毕设1 天前
基于SpringBoot军事纪念馆管理系统设计与实现-附源码
java·spring boot·后端
岁月宁静1 天前
从零拆解 AI 语音模拟面试系统
人工智能·python·agent
benchmark_cc1 天前
个人开发者接入五档盘口:用 QuantDash 读取单只股票的验收清单与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
这个昵称不容易1 天前
SpringBoot 医疗病历交互系统的设计与实现:192 个 Java 文件、256 个接口、22 张表,附真实运行截图
java·springboot·毕设
ZhengEnCi1 天前
项目越写越乱?先别改架构:用一次目录重排 + 一份可复算的体检脚本把乱治住
python·架构·ai编程