代码示例
from openpyxl import Workbook
# 创建一个新的 Excel 文件
workbook = Workbook()
sheet = workbook.active
# 添加一些示例数据到 Excel
data = [
["Name", "Age"],
["Alice", 30],
["Bob", 25],
["Charlie", 35]
]
for row in data:
sheet.append(row)
# 保存 Excel 文件
save_path = r"F:\work\python\files\password.xlsx"
workbook.save(save_path)
# 加密 Excel 文件
from win32com import client
xl = client.Dispatch("Excel.Application")
xl.DisplayAlerts = False # 不显示警告信息
xl.Visible = False
xl.Workbooks.Open(save_path)
# 设置密码保护
xl.ActiveWorkbook.Password = "123456"
# 设置文档加密
xl.ActiveWorkbook.SaveAs(save_path, Password="123456")
xl.ActiveWorkbook.Close(SaveChanges=0)
xl.Quit()
print("Excel 文件 'password.xlsx' 已生成并使用文档加密和密码保护")