用 with 语句 win32 打开原生 ppt

154 篇文章 4 订阅
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.")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值