import win32com.client
import pythoncom
class PowerPointContext:
def __init__(self, visible=True):
self.powerpoint = None
self.visible = visible
def __enter__(self):
pythoncom.CoInitialize() # 初始化 COM
self.powerpoint = win32com.client.Dispatch("PowerPoint.Application")
self.powerpoint.Visible = self.visible
return self.powerpoint
def __exit__(self, exc_type, exc_val, exc_tb):
if self.powerpoint:
try:
self.powerpoint.Quit()
except:
pass # 忽略关闭时的错误
pythoncom.CoUninitialize() # 清理 COM
return False # 返回 False 使得异常可以传播
# 使用示例
with PowerPointContext() as ppt:
presentation = ppt.Presentations.Add()
slide = presentation.Slides.Add(1, 1)
textbox = slide.Shapes.AddTextbox(1, 100, 100, 300, 50)
textbox.TextFrame.TextRange.Text = "Hello, PowerPoint!"
presentation.SaveAs(r"E:\code\file.pptx")
print("PowerPoint file created successfully.")
05-27
3644
09-13
390
05-26