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)