Python 调用 Office

2020-11-30 2:1

安装库

pip install pywin32

Excel 转 PDF

        import os
        from win32com.client import Dispatch,constants,gencache,DispatchEx

        app=DispatchEx('Excel.Application')
        app.Visible=False
        app.DisplayAlerts=False

        wkbk=app.Workbooks.Open(os.path.abspath('./test.xlsx'),False)
        wkbk.ExportAsFixedFormat(0,os.path.abspath('./output.pdf'))
        wkbk.Close(False)

        app.Quit()
      

创建 Outlook 邮件并保存到草稿箱

        import os
        from win32com.client import Dispatch,constants,gencache,DispatchEx

        app=DispatchEx('Outlook.Application')

        mail=app.CreateItem(0)
        mail.Subject='测试邮件标题'
        mail.To='test_user1@test.com;test_user2@test.com'
        mail.CC='test_user1@test.com;test_user2@test.com;test_user3@test.com'
        mail.body='测试邮件正文1\r\n测试邮件正文2'
        mail.Attachments.Add(os.path.abspath('./attachment1.jpg'))
        mail.Attachments.Add(os.path.abspath('./attachment2.pdf'))
        mail.Save()

        app.Quit()