CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-xlwings

Python library for seamless bidirectional communication between Python and Excel across Windows and macOS platforms.

Overview
Eval results
Files

core-objects.mddocs/

Core Excel Objects

Primary classes for interacting with Excel applications, workbooks, worksheets, and cell ranges. These form the foundation of xlwings' object model and provide the main interface for Excel automation across all supported platforms.

Capabilities

App - Excel Application

Represents an Excel application instance. The App class provides control over the Excel application itself, including visibility, calculation settings, and lifecycle management.

class App:
    def __init__(self, visible=None, spec=None, add_book=True, xl=None):
        """
        Create or connect to an Excel application.
        
        Args:
            visible (bool, optional): Make Excel visible. Defaults to False.
            spec (str, optional): App specification for engine selection.
            add_book (bool): Whether to add a new workbook. Defaults to True.
            xl (object, optional): Existing Excel application object.
        """
    
    def activate(self):
        """Activate the Excel application (bring to foreground)."""
    
    def calculate(self, calculation=None):
        """
        Trigger Excel calculation.
        
        Args:
            calculation (str, optional): Calculation type ('xlCalculationAutomatic', 
                'xlCalculationManual', 'xlCalculationSemiautomatic').
        """
    
    def kill(self):
        """Forcefully terminate the Excel application process."""
    
    def quit(self):
        """Quit the Excel application gracefully."""
    
    @property
    def books(self) -> Books:
        """Collection of all workbooks in this application."""
    
    @property
    def calculation(self) -> str:
        """Get/set calculation mode ('automatic', 'manual', 'semiautomatic')."""
    
    @calculation.setter
    def calculation(self, value: str): ...
    
    @property
    def display_alerts(self) -> bool:
        """Get/set whether Excel displays alerts and dialog boxes."""
    
    @display_alerts.setter
    def display_alerts(self, value: bool): ...
    
    @property
    def screen_updating(self) -> bool:
        """Get/set whether Excel updates the screen during operations."""
    
    @screen_updating.setter  
    def screen_updating(self, value: bool): ...
    
    @property
    def visible(self) -> bool:
        """Get/set Excel application visibility."""
    
    @visible.setter
    def visible(self, value: bool): ...
    
    @property
    def version(self) -> VersionNumber:
        """Excel version number object with major, minor attributes."""
    
    @property
    def api(self):
        """Access to the native Excel application object."""

Usage example:

import xlwings as xw

# Create new Excel application (invisible by default)
app = xw.App()

# Create visible Excel application
app = xw.App(visible=True)

# Configure application settings
app.display_alerts = False
app.screen_updating = False
app.calculation = 'manual'

# Access workbooks
wb = app.books.add()

# Clean up
app.quit()

Book - Excel Workbook

Represents an Excel workbook (.xlsx, .xlsm, etc.). The Book class manages workbook-level operations including saving, closing, and accessing sheets.

class Book:
    def activate(self):
        """Activate this workbook (bring to foreground)."""
    
    def close(self):
        """Close the workbook."""
    
    def save(self, path=None):
        """
        Save the workbook.
        
        Args:
            path (str, optional): File path. If None, saves to current location.
        """
    
    def fullname(self) -> str:
        """Full path of the workbook file."""
    
    def json(self):
        """Export workbook data as JSON."""
    
    @property
    def app(self) -> App:
        """The Excel application containing this workbook."""
    
    @property 
    def name(self) -> str:
        """Workbook filename."""
    
    @property
    def sheets(self) -> Sheets:
        """Collection of all worksheets in this workbook."""
    
    @property
    def names(self) -> Names:
        """Collection of all named ranges in this workbook."""
    
    @property
    def selection(self) -> Range:
        """Currently selected range in the active sheet."""
    
    @property
    def api(self):
        """Access to the native Excel workbook object."""

Usage example:

import xlwings as xw

# Open existing workbook
wb = xw.books.open('/path/to/workbook.xlsx')

# Create new workbook
app = xw.App()
wb = app.books.add()

# Work with workbook
wb.name  # Get filename
wb.fullname()  # Get full path
ws = wb.sheets[0]  # Access first sheet

# Save and close
wb.save('/path/to/new_location.xlsx')
wb.close()

Sheet - Excel Worksheet

Represents an Excel worksheet within a workbook. The Sheet class provides access to worksheet-level operations and serves as the primary interface for accessing ranges.

class Sheet:
    def activate(self):
        """Activate this worksheet (make it the active sheet)."""
    
    def clear(self):
        """Clear all content and formatting from the worksheet."""
    
    def delete(self):
        """Delete this worksheet from the workbook."""
    
    def copy(self, before=None, after=None):
        """
        Copy this worksheet.
        
        Args:
            before (Sheet, optional): Sheet to insert before.
            after (Sheet, optional): Sheet to insert after.
        """
    
    def range(self, cell1, cell2=None) -> Range:
        """
        Create a Range object.
        
        Args:
            cell1 (str or tuple): Cell address like 'A1' or (row, col) tuple.
            cell2 (str or tuple, optional): End cell for range.
            
        Returns:
            Range: Range object representing the specified cells.
        """
    
    @property
    def book(self) -> Book:
        """The workbook containing this worksheet."""
    
    @property
    def name(self) -> str:
        """Worksheet name."""
    
    @name.setter
    def name(self, value: str): ...
    
    @property
    def charts(self) -> Charts:
        """Collection of all charts in this worksheet."""
    
    @property
    def pictures(self) -> Pictures:
        """Collection of all pictures in this worksheet."""
    
    @property
    def shapes(self) -> Shapes:
        """Collection of all shapes in this worksheet."""
    
    @property
    def used_range(self) -> Range:
        """Range representing all used cells in the worksheet."""
    
    @property
    def api(self):
        """Access to the native Excel worksheet object."""

Usage example:

import xlwings as xw

wb = xw.books.add()
ws = wb.sheets[0]

# Rename worksheet
ws.name = 'MyData'

# Access ranges
ws.range('A1').value = 'Hello World'
ws.range('A1:C3').value = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Get used range
data_range = ws.used_range
print(data_range.address)  # e.g., '$A$1:$C$3'

# Work with charts and pictures
chart = ws.charts.add()
ws.pictures.add('/path/to/image.png')

Range - Excel Cell Range

The most feature-rich class in xlwings, representing Excel cell ranges. Range provides comprehensive functionality for data manipulation, formatting, navigation, and conversion between Python and Excel data types.

class Range:
    # Data operations
    def clear(self):
        """Clear both content and formatting from the range."""
    
    def clear_contents(self):
        """Clear only content, preserve formatting."""
    
    def copy(self, destination=None):
        """
        Copy the range to clipboard or destination.
        
        Args:
            destination (Range, optional): Target range for paste operation.
        """
    
    def paste(self, paste=None):
        """
        Paste clipboard content to this range.
        
        Args:
            paste (str, optional): Paste type ('xlPasteValues', 'xlPasteFormats', etc.).
        """
    
    def delete(self, shift=None):
        """
        Delete the range and shift surrounding cells.
        
        Args:
            shift (str, optional): Shift direction ('xlShiftUp', 'xlShiftToLeft').
        """
    
    def merge(self, across=False):
        """
        Merge cells in the range.
        
        Args:
            across (bool): Merge across columns only if True.
        """
    
    # Navigation and sizing
    def end(self, direction):
        """
        Navigate to end of continuous data in given direction.
        
        Args:
            direction (str): Direction ('up', 'down', 'left', 'right').
            
        Returns:
            Range: Range at the end of continuous data.
        """
    
    def expand(self, mode='table'):
        """
        Expand range to include surrounding data.
        
        Args:
            mode (str): Expansion mode ('table', 'down', 'right').
            
        Returns:
            Range: Expanded range.
        """
    
    def offset(self, row_offset=0, column_offset=0):
        """
        Create new range offset from current range.
        
        Args:
            row_offset (int): Rows to offset (positive = down, negative = up).
            column_offset (int): Columns to offset (positive = right, negative = left).
            
        Returns:
            Range: New range at offset position.
        """
    
    def resize(self, nrows=None, ncols=None):
        """
        Resize the range to specified dimensions.
        
        Args:
            nrows (int, optional): Number of rows. None keeps current.
            ncols (int, optional): Number of columns. None keeps current.
            
        Returns:
            Range: Resized range.
        """
    
    # Data properties
    @property
    def value(self):
        """
        Get/set cell values. Supports various Python data types:
        - Single values: int, float, str, datetime, None
        - Lists and nested lists for multi-cell ranges
        - pandas DataFrames and Series
        - NumPy arrays
        """
    
    @value.setter
    def value(self, data): ...
    
    @property
    def formula(self) -> str:
        """Get/set Excel formula (single cell)."""
    
    @formula.setter
    def formula(self, value: str): ...
    
    @property
    def formula_array(self) -> str:
        """Get/set array formula."""
    
    @formula_array.setter
    def formula_array(self, value: str): ...
    
    # Range properties
    @property
    def address(self) -> str:
        """Range address in A1 notation (e.g., '$A$1:$C$3')."""
    
    @property
    def column(self) -> int:
        """First column number (1-based)."""
    
    @property
    def row(self) -> int:
        """First row number (1-based)."""
    
    @property
    def shape(self) -> tuple:
        """Range dimensions as (rows, columns) tuple."""
    
    @property
    def size(self) -> int:
        """Total number of cells in the range."""
    
    @property
    def width(self) -> float:
        """Range width in points."""
    
    @property
    def height(self) -> float:
        """Range height in points."""
    
    @property
    def current_region(self) -> Range:
        """Range representing the continuous data region around this range."""
    
    # Formatting properties  
    @property
    def color(self):
        """Get/set background color as RGB tuple or None."""
    
    @color.setter
    def color(self, value): ...
    
    @property
    def font(self):
        """Access to font formatting properties."""
    
    @property
    def number_format(self) -> str:
        """Get/set number format string."""
    
    @number_format.setter
    def number_format(self, value: str): ...
    
    # Additional properties
    @property
    def note(self):
        """Get/set cell note/comment."""
    
    @note.setter
    def note(self, value): ...
    
    @property
    def hyperlink(self) -> str:
        """Get/set hyperlink URL."""
    
    @hyperlink.setter
    def hyperlink(self, value: str): ...
    
    @property
    def wrap_text(self) -> bool:
        """Get/set text wrapping."""
    
    @wrap_text.setter
    def wrap_text(self, value: bool): ...
    
    @property
    def columns(self) -> RangeColumns:
        """Column collection for this range."""
    
    @property
    def rows(self) -> RangeRows:
        """Row collection for this range."""
    
    @property
    def api(self):
        """Access to the native Excel range object."""

Usage examples:

import xlwings as xw
import pandas as pd
import numpy as np

wb = xw.books.add()
ws = wb.sheets[0]

# Basic value operations
ws.range('A1').value = 'Hello'
ws.range('B1').value = 42
ws.range('C1').value = 3.14159

# Multi-cell operations
ws.range('A2:C4').value = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
data = ws.range('A2:C4').value
print(data)  # Nested list

# pandas DataFrame integration
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Score': [85.5, 90.2, 78.9]
})
ws.range('E1').value = df

# Read DataFrame back
df_range = ws.range('E1').expand()
df_back = df_range.options(pd.DataFrame, header=1, index=False).value

# NumPy array support
arr = np.random.rand(5, 3)
ws.range('A10').value = arr

# Range navigation
start_range = ws.range('A1')
end_range = start_range.end('down')  # Navigate to last non-empty cell
current_region = start_range.current_region  # Get continuous data region

# Range manipulation
ws.range('A1:C1').merge()  # Merge cells
ws.range('A5:C5').color = (255, 255, 0)  # Yellow background
ws.range('A6').font.bold = True

# Formulas
ws.range('D1').formula = '=SUM(A1:C1)'
ws.range('D2:D4').formula = 'A2:A4 * 2'

Named Ranges

Represents Excel named ranges that provide meaningful names for cell references throughout the workbook.

class Name:
    def delete(self):
        """Delete this named range."""
    
    @property
    def name(self) -> str:
        """The name of the named range."""
    
    @property
    def refers_to(self) -> str:
        """Formula string that the name refers to."""
    
    @property
    def refers_to_range(self) -> Range:
        """Range object that the name refers to."""
    
    @property
    def api(self):
        """Access to the native Excel name object."""

Usage example:

import xlwings as xw

wb = xw.books.add()
ws = wb.sheets[0]

# Create data and named range
ws.range('A1:C3').value = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
wb.names.add('MyData', 'Sheet1!$A$1:$C$3')

# Access named range
named_range = wb.names['MyData']
print(named_range.refers_to)  # '=Sheet1!$A$1:$C$3' 

# Use named range in formulas
ws.range('D1').formula = '=SUM(MyData)'

# Get range object from name
data_range = named_range.refers_to_range
print(data_range.value)

Types

# Collection types
Apps = Collection[App]
Books = Collection[Book]  
Sheets = Collection[Sheet]
Charts = Collection[Chart]
Pictures = Collection[Picture]
Shapes = Collection[Shape]
Names = Collection[Name]
RangeColumns = Collection  # Columns within a range
RangeRows = Collection     # Rows within a range

# Utility types
class VersionNumber:
    """Excel version number with major/minor properties."""
    @property
    def major(self) -> int: ...
    @property
    def minor(self) -> int: ...

Install with Tessl CLI

npx tessl i tessl/pypi-xlwings

docs

charts-visualization.md

cli.md

collections-functions.md

constants.md

conversion.md

core-objects.md

index.md

pro-features.md

udfs.md

utilities.md

tile.json