pywin32 (Python for Windows Extensions)

311 · active · verified Sat Mar 28

pywin32 is an open-source Python library that provides extensive access to many Windows APIs and the Component Object Model (COM). It enables Python scripts to automate Windows applications like Excel and Outlook, interact with system services, manage the clipboard, and perform various other Windows-specific operations. The current version is 311, and the project maintains a frequent release cadence, offering incremental improvements and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic COM automation by launching Microsoft Excel, making it visible, adding a new workbook, and writing text to specific cells. It showcases the common pattern of using `win32com.client.Dispatch` or `GetActiveObject` to control COM applications. Ensure Excel is installed for this example to run.

import win32com.client
import os

try:
    # Try to get an active Excel instance, or create a new one
    excel = win32com.client.GetActiveObject("Excel.Application")
except Exception: # pythoncom.com_error if pywin32 is installed correctly
    excel = win32com.client.Dispatch("Excel.Application")

excel.Visible = True # Make Excel visible
workbook = excel.Workbooks.Add() # Add a new workbook
sheet = workbook.Sheets(1) # Get the first sheet

sheet.Cells(1, 1).Value = "Hello from pywin32!"
sheet.Cells(2, 1).Value = "Automating Windows with Python."

print("Excel opened and data written. Please check your Excel application.")
print("You might need to close Excel manually after inspection.")

view raw JSON →