API Documentation

The xlwings object model is very similar to the one used by Excel VBA but the hierarchy is flattened. An example:

VBA:

Workbooks("Book1").Sheets("Sheet1").Range("A1").Value = "Some Text"

xlwings:

wb = Workbook("Book1")
Range("Sheet1", "A1").value = "Some Text"

Top-level functions

xlwings.view(obj)

Opens a new workbook and displays an object on its first sheet.

Parameters:obj (any type with built-in converter) –

the object to display

>>> import xlwings as xw
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
>>> xw.view(df)

New in version 0.7.1.

Application

class xlwings.Application(wkb)

Application is dependent on the Workbook since there might be different application instances on Windows.

version

Returns Excel’s version string.

New in version 0.5.0.

quit()

Quits the application without saving any workbooks.

New in version 0.3.3.

screen_updating

True if screen updating is turned on. Read/write Boolean.

New in version 0.3.3.

visible

Gets or sets the visibility of Excel to True or False. This property can also be conveniently set during instantiation of a new Workbook: Workbook(app_visible=False)

New in version 0.3.3.

calculation

Returns or sets a Calculation value that represents the calculation mode.

Example

>>> from xlwings import Workbook, Application
>>> from xlwings.constants import Calculation
>>> wb = Workbook()
>>> Application(wkb=wb).calculation = Calculation.xlCalculationManual

New in version 0.3.3.

calculate()

Calculates all open Workbooks

New in version 0.3.6.

Workbook

In order to use xlwings, instantiating a workbook object is always the first thing to do:

class xlwings.Workbook(fullname=None, xl_workbook=None, app_visible=True, app_target=None)

Workbook connects an Excel Workbook with Python. You can create a new connection from Python with

  • a new workbook: wb = Workbook()
  • the active workbook: wb = Workbook.active()
  • an unsaved workbook: wb = Workbook('Book1')
  • a saved (open) workbook by name (incl. xlsx etc): wb = Workbook('MyWorkbook.xlsx')
  • a saved (open or closed) workbook by path: wb = Workbook(r'C:\path\to\file.xlsx')
Keyword Arguments:
 
  • fullname (str, default None) – Full path or name (incl. xlsx, xlsm etc.) of existing workbook or name of an unsaved workbook.
  • xl_workbook (pywin32 or appscript Workbook object, default None) – This enables to turn existing Workbook objects of the underlying libraries into xlwings objects
  • app_visible (boolean, default True) – The resulting Workbook will be visible by default. To open it without showing a window, set app_visible=False. Or, to not alter the visibility (e.g., if Excel is already running), set app_visible=None. Note that this property acts on the whole Excel instance, not just the specific Workbook.
  • app_target (str, default None) –

    Mac-only, use the full path to the Excel application, e.g. /Applications/Microsoft Office 2011/Microsoft Excel or /Applications/Microsoft Excel

    On Windows, if you want to change the version of Excel that xlwings talks to, go to Control Panel > Programs and Features and Repair the Office version that you want as default.

To create a connection when the Python function is called from Excel, use:

wb = Workbook.caller()

classmethod active(app_target=None)

Returns the Workbook that is currently active or has been active last. On Windows, this works across all instances.

New in version 0.4.1.

classmethod caller()

Creates a connection when the Python function is called from Excel:

wb = Workbook.caller()

Always pack the Workbook call into the function being called from Excel, e.g.:

def my_macro():
   wb = Workbook.caller()
   Range('A1').value = 1

To be able to easily invoke such code from Python for debugging, use Workbook.set_mock_caller().

New in version 0.3.0.

static set_mock_caller(fullpath)

Sets the Excel file which is used to mock Workbook.caller() when the code is called from within Python.

Examples

# This code runs unchanged from Excel and Python directly
import os
from xlwings import Workbook, Range

def my_macro():
    wb = Workbook.caller()
    Range('A1').value = 'Hello xlwings!'

if __name__ == '__main__':
    # Mock the calling Excel file
    Workbook.set_mock_caller(r'C:\path\to\file.xlsx')
    my_macro()

New in version 0.3.1.

classmethod current()

Returns the current Workbook object, i.e. the default Workbook used by Sheet, Range and Chart if not specified otherwise. On Windows, in case there are various instances of Excel running, opening an existing or creating a new Workbook through Workbook() is acting on the same instance of Excel as this Workbook. Use like this: Workbook.current().

New in version 0.2.2.

set_current()

This makes the Workbook the default that Sheet, Range and Chart use if not specified otherwise. On Windows, in case there are various instances of Excel running, opening an existing or creating a new Workbook through Workbook() is acting on the same instance of Excel as this Workbook.

New in version 0.2.2.

get_selection()

Returns the currently selected cells from Excel as Range object.

Example

>>> import xlwings as xw
>>> wb = xw.Workbook.active()
>>> wb.get_selection()
<Range on Sheet 'Sheet1' of Workbook 'Workbook1'>
>>> wb.get_selection.value
[[1.0, 2.0], [3.0, 4.0]]
>>> wb.get_selection().options(transpose=True).value
[[1.0, 3.0], [2.0, 4.0]]
Returns:
Return type:Range object
close()

Closes the Workbook without saving it.

New in version 0.1.1.

save(path=None)

Saves the Workbook. If a path is being provided, this works like SaveAs() in Excel. If no path is specified and if the file hasn’t been saved previously, it’s being saved in the current working directory with the current filename. Existing files are overwritten without prompting.

Parameters:path (str, default None) – Full path to the workbook

Example

>>> from xlwings import Workbook
>>> wb = Workbook()
>>> wb.save()
>>> wb.save(r'C:\path\to\new_file_name.xlsx')

New in version 0.3.1.

static get_xl_workbook(wkb)

Returns the xl_workbook_current if wkb is None, otherwise the xl_workbook of wkb. On Windows, xl_workbook is a pywin32 COM object, on Mac it’s an appscript object.

Parameters:wkb (Workbook or None) – Workbook object
static open_template()

Creates a new Excel file with the xlwings VBA module already included. This method must be called from an interactive Python shell:

>>> Workbook.open_template()

New in version 0.3.3.

names

A collection of all the (platform-specific) name objects in the application or workbook. Each name object represents a defined name for a range of cells (built-in or custom ones).

New in version 0.4.0.

macro(name)

Runs a Sub or Function in Excel VBA.

name : Name of Sub or Function with or without module name, e.g. 'Module1.MyMacro' or 'MyMacro'

This VBA function:

Function MySum(x, y)
    MySum = x + y
End Function

can be accessed like this:

>>> wb = xw.Workbook.active()
>>> my_sum = wb.macro('MySum')
>>> my_sum(1, 2)
3

New in version 0.7.1.

Sheet

Sheet objects allow you to interact with anything directly related to a Sheet.

class xlwings.Sheet(sheet, wkb=None)

Represents a Sheet of the current Workbook. Either call it with the Sheet name or index:

Sheet('Sheet1')
Sheet(1)
Parameters:sheet (str or int) – Sheet name or index
Keyword Arguments:
 wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().

New in version 0.2.3.

activate()

Activates the sheet.

autofit(axis=None)

Autofits the width of either columns, rows or both on a whole Sheet.

Parameters:axis (string, default None) –
  • To autofit rows, use one of the following: rows or r
  • To autofit columns, use one of the following: columns or c
  • To autofit rows and columns, provide no arguments

Examples

# Autofit columns
Sheet('Sheet1').autofit('c')
# Autofit rows
Sheet('Sheet1').autofit('r')
# Autofit columns and rows
Range('Sheet1').autofit()

New in version 0.2.3.

clear_contents()

Clears the content of the whole sheet but leaves the formatting.

clear()

Clears the content and formatting of the whole sheet.

name

Get or set the name of the Sheet.

index

Returns the index of the Sheet.

classmethod active(wkb=None)

Returns the active Sheet. Use like so: Sheet.active()

classmethod add(name=None, before=None, after=None, wkb=None)

Creates a new worksheet: the new worksheet becomes the active sheet. If neither before nor after is specified, the new Sheet will be placed at the end.

Parameters:
  • name (str, default None) – Sheet name, defaults to Excel standard name
  • before (str or int, default None) – Sheet name or index
  • after (str or int, default None) – Sheet name or index
Returns:

Return type:

Sheet object

Examples

>>> Sheet.add()  # Place at end with default name
>>> Sheet.add('NewSheet', before='Sheet1')  # Include name and position
>>> new_sheet = Sheet.add(after=3)
>>> new_sheet.index
4

New in version 0.2.3.

static count(wkb=None)

Counts the number of Sheets.

Keyword Arguments:
 wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().

Examples

>>> Sheet.count()
3

New in version 0.2.3.

static all(wkb=None)

Returns a list with all Sheet objects.

Keyword Arguments:
 wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().

Examples

>>> Sheet.all()
[<Sheet 'Sheet1' of Workbook 'Book1'>, <Sheet 'Sheet2' of Workbook 'Book1'>]
>>> [i.name.lower() for i in Sheet.all()]
['sheet1', 'sheet2']
>>> [i.autofit() for i in Sheet.all()]

New in version 0.2.3.

delete()

Deletes the Sheet.

Range

The xlwings Range object represents a block of contiguous cells in Excel.

class xlwings.Range(*args, wkb=None)

A Range object can be instantiated with the following arguments:

Range('A1')          Range('Sheet1', 'A1')          Range(1, 'A1')
Range('A1:C3')       Range('Sheet1', 'A1:C3')       Range(1, 'A1:C3')
Range((1,2))         Range('Sheet1, (1,2))          Range(1, (1,2))
Range((1,1), (3,3))  Range('Sheet1', (1,1), (3,3))  Range(1, (1,1), (3,3))
Range('NamedRange')  Range('Sheet1', 'NamedRange')  Range(1, 'NamedRange')

The Sheet can also be provided as Sheet object:

sh = Sheet(1)
Range(sh, 'A1')

If no worksheet name is provided as first argument, it will take the Range from the active sheet.

You usually want to go for Range(...).value to get the values (as list of lists). You can influence the reading/writing behavior by making use of Converters and Options and their options: Range(...).options(...).value

Parameters:*args – Definition of sheet (optional) and Range in the above described combinations.
Keyword Arguments:
 wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current()`.
options(convert=None, **options)

Allows you to set a converter and their options. Converters define how Excel Ranges and their values are being converted both during reading and writing operations. If no explicit converter is specified, the base converter is being applied, see Converters and Options.

Parameters:

convert (object, default None) – A converter, e.g. dict, np.array, pd.DataFrame, pd.Series, defaults to default converter

Keyword Arguments:
 
  • ndim (int, default None) – number of dimensions
  • numbers (type, default None) – type of numbers, e.g. int
  • dates (type, default None) – e.g. datetime.date defaults to datetime.datetime
  • empty (object, default None) – transformation of empty cells
  • transpose (Boolean, default False) – transpose values
  • expand (str, default None) –

    One of 'table', 'vertical', 'horizontal', see also Range.table etc

    => For converter-specific options, see Converters and Options.

Returns:

Return type:

Range object

New in version 0.7.0.

is_cell()

Returns True if the Range consists of a single Cell otherwise False.

New in version 0.1.1.

is_row()

Returns True if the Range consists of a single Row otherwise False.

New in version 0.1.1.

is_column()

Returns True if the Range consists of a single Column otherwise False.

New in version 0.1.1.

is_table()

Returns True if the Range consists of a 2d array otherwise False.

New in version 0.1.1.

shape

Tuple of Range dimensions.

New in version 0.3.0.

size

Number of elements in the Range.

New in version 0.3.0.

value

Gets and sets the values for the given Range.

Returns:Empty cells are set to None.
Return type:object
formula

Gets or sets the formula for the given Range.

formula_array

Gets or sets an array formula for the given Range.

New in version 0.7.1.

table

Returns a contiguous Range starting with the indicated cell as top-left corner and going down and right as long as no empty cell is hit.

Keyword Arguments:
 strict (boolean, default False) – True stops the table at empty cells even if they contain a formula. Less efficient than if set to False.
Returns:
Return type:Range object

Examples

To get the values of a contiguous range or clear its contents use:

Range('A1').table.value
Range('A1').table.clear_contents()
vertical

Returns a contiguous Range starting with the indicated cell and going down as long as no empty cell is hit. This corresponds to Ctrl-Shift-DownArrow in Excel.

Parameters:strict (bool, default False) – True stops the table at empty cells even if they contain a formula. Less efficient than if set to False.
Returns:
Return type:Range object

Examples

To get the values of a contiguous range or clear its contents use:

Range('A1').vertical.value
Range('A1').vertical.clear_contents()
horizontal

Returns a contiguous Range starting with the indicated cell and going right as long as no empty cell is hit.

Keyword Arguments:
 strict (bool, default False) – True stops the table at empty cells even if they contain a formula. Less efficient than if set to False.
Returns:
Return type:Range object

Examples

To get the values of a contiguous Range or clear its contents use:

Range('A1').horizontal.value
Range('A1').horizontal.clear_contents()
current_region

This property returns a Range object representing a range bounded by (but not including) any combination of blank rows and blank columns or the edges of the worksheet. It corresponds to Ctrl-* on Windows and Shift-Ctrl-Space on Mac.

Returns:
Return type:Range object
number_format

Gets and sets the number_format of a Range.

Examples

>>> Range('A1').number_format
'General'
>>> Range('A1:C3').number_format = '0.00%'
>>> Range('A1:C3').number_format
'0.00%'

New in version 0.2.3.

clear()

Clears the content and the formatting of a Range.

clear_contents()

Clears the content of a Range but leaves the formatting.

column_width

Gets or sets the width, in characters, of a Range. One unit of column width is equal to the width of one character in the Normal style. For proportional fonts, the width of the character 0 (zero) is used.

If all columns in the Range have the same width, returns the width. If columns in the Range have different widths, returns None.

column_width must be in the range: 0 <= column_width <= 255

Note: If the Range is outside the used range of the Worksheet, and columns in the Range have different widths, returns the width of the first column.

Returns:
Return type:float

New in version 0.4.0.

row_height

Gets or sets the height, in points, of a Range. If all rows in the Range have the same height, returns the height. If rows in the Range have different heights, returns None.

row_height must be in the range: 0 <= row_height <= 409.5

Note: If the Range is outside the used range of the Worksheet, and rows in the Range have different heights, returns the height of the first row.

Returns:
Return type:float

New in version 0.4.0.

width

Returns the width, in points, of a Range. Read-only.

Returns:
Return type:float

New in version 0.4.0.

height

Returns the height, in points, of a Range. Read-only.

Returns:
Return type:float

New in version 0.4.0.

left

Returns the distance, in points, from the left edge of column A to the left edge of the range. Read-only.

Returns:
Return type:float

New in version 0.6.0.

top

Returns the distance, in points, from the top edge of row 1 to the top edge of the range. Read-only.

Returns:
Return type:float

New in version 0.6.0.

autofit(axis=None)

Autofits the width of either columns, rows or both.

Parameters:axis (string or integer, default None) –
  • To autofit rows, use one of the following: rows or r
  • To autofit columns, use one of the following: columns or c
  • To autofit rows and columns, provide no arguments

Examples

# Autofit column A
Range('A:A').autofit('c')
# Autofit row 1
Range('1:1').autofit('r')
# Autofit columns and rows, taking into account Range('A1:E4')
Range('A1:E4').autofit()
# AutoFit rows, taking into account Range('A1:E4')
Range('A1:E4').autofit('rows')

New in version 0.2.2.

get_address(row_absolute=True, column_absolute=True, include_sheetname=False, external=False)

Returns the address of the range in the specified format.

Parameters:
  • row_absolute (bool, default True) – Set to True to return the row part of the reference as an absolute reference.
  • column_absolute (bool, default True) – Set to True to return the column part of the reference as an absolute reference.
  • include_sheetname (bool, default False) – Set to True to include the Sheet name in the address. Ignored if external=True.
  • external (bool, default False) – Set to True to return an external reference with workbook and worksheet name.
Returns:

Return type:

str

Examples

>>> Range((1,1)).get_address()
'$A$1'
>>> Range((1,1)).get_address(False, False)
'A1'
>>> Range('Sheet1', (1,1), (3,3)).get_address(True, False, True)
'Sheet1!A$1:C$3'
>>> Range('Sheet1', (1,1), (3,3)).get_address(True, False, external=True)
'[Workbook1]Sheet1!A$1:C$3'

New in version 0.2.3.

Returns the hyperlink address of the specified Range (single Cell only)

Examples

>>> Range('A1').value
'www.xlwings.org'
>>> Range('A1').hyperlink
'http://www.xlwings.org'

New in version 0.3.0.

Adds a hyperlink to the specified Range (single Cell)

Parameters:
  • address (str) – The address of the hyperlink.
  • text_to_display (str, default None) – The text to be displayed for the hyperlink. Defaults to the hyperlink address.
  • screen_tip (str, default None) – The screen tip to be displayed when the mouse pointer is paused over the hyperlink. Default is set to ‘<address> - Click once to follow. Click and hold to select this cell.’

New in version 0.3.0.

color

Gets and sets the background color of the specified Range.

To set the color, either use an RGB tuple (0, 0, 0) or a color constant. To remove the background, set the color to None, see Examples.

Returns:RGB
Return type:tuple

Examples

>>> Range('A1').color = (255,255,255)
>>> from xlwings import RgbColor
>>> Range('A2').color = RgbColor.rgbAqua
>>> Range('A2').color
(0, 255, 255)
>>> Range('A2').color = None
>>> Range('A2').color is None
True

New in version 0.3.0.

resize(row_size=None, column_size=None)

Resizes the specified Range

Parameters:
  • row_size (int > 0) – The number of rows in the new range (if None, the number of rows in the range is unchanged).
  • column_size (int > 0) – The number of columns in the new range (if None, the number of columns in the range is unchanged).
Returns:

Range

Return type:

Range object

New in version 0.3.0.

offset(row_offset=None, column_offset=None)

Returns a Range object that represents a Range that’s offset from the specified range.

Returns:Range
Return type:Range object

New in version 0.3.0.

column

Returns the number of the first column in the in the specified range. Read-only.

Returns:
Return type:Integer

New in version 0.3.5.

row

Returns the number of the first row in the in the specified range. Read-only.

Returns:
Return type:Integer

New in version 0.3.5.

last_cell

Returns the bottom right cell of the specified range. Read-only.

Returns:
Return type:Range object

Example

>>> rng = Range('A1').table
>>> rng.last_cell.row, rng.last_cell.column
(4, 5)

New in version 0.3.5.

name

Sets or gets the name of a Range.

To delete a named Range, use del wb.names['NamedRange'] if wb is your Workbook object.

New in version 0.4.0.

Shape

class xlwings.Shape(*args, **kwargs)

A Shape object represents an existing Excel shape and can be instantiated with the following arguments:

Shape(1)            Shape('Sheet1', 1)              Shape(1, 1)
Shape('Shape 1')    Shape('Sheet1', 'Shape 1')      Shape(1, 'Shape 1')

The Sheet can also be provided as Sheet object:

sh = Sheet(1)
Shape(sh, 'Shape 1')

If no Worksheet is provided as first argument, it will take the Shape from the active Sheet.

Parameters:*args – Definition of Sheet (optional) and shape in the above described combinations.
Keyword Arguments:
 wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().

New in version 0.5.0.

name

Returns or sets a String value representing the name of the object.

New in version 0.5.0.

left

Returns or sets a value that represents the distance, in points, from the left edge of the object to the left edge of column A.

New in version 0.5.0.

top

Returns or sets a value that represents the distance, in points, from the top edge of the topmost shape in the shape range to the top edge of the worksheet.

New in version 0.5.0.

width

Returns or sets a value that represents the width, in points, of the object.

New in version 0.5.0.

height

Returns or sets a value that represents the height, in points, of the object.

New in version 0.5.0.

delete()

Deletes the object.

New in version 0.5.0.

activate()

Activates the object.

New in version 0.5.0.

Chart

Note

The chart object is currently still lacking a lot of important methods/attributes.

class xlwings.Chart(*args, **kwargs)

Bases: xlwings.main.Shape

A Chart object represents an existing Excel chart and can be instantiated with the following arguments:

Chart(1)            Chart('Sheet1', 1)              Chart(1, 1)
Chart('Chart 1')    Chart('Sheet1', 'Chart 1')      Chart(1, 'Chart 1')

The Sheet can also be provided as Sheet object:

sh = Sheet(1)
Chart(sh, 'Chart 1')

If no Worksheet is provided as first argument, it will take the Chart from the active Sheet.

To insert a new Chart into Excel, create it as follows:

Chart.add()
Parameters:*args – Definition of Sheet (optional) and chart in the above described combinations.
Keyword Arguments:
 wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().

Example

>>> from xlwings import Workbook, Range, Chart, ChartType
>>> wb = Workbook()
>>> Range('A1').value = [['Foo1', 'Foo2'], [1, 2]]
>>> chart = Chart.add(source_data=Range('A1').table, chart_type=ChartType.xlLine)
>>> chart.name
'Chart1'
>>> chart.chart_type = ChartType.xl3DArea
activate()

Activates the object.

New in version 0.5.0.

delete()

Deletes the object.

New in version 0.5.0.

height

Returns or sets a value that represents the height, in points, of the object.

New in version 0.5.0.

left

Returns or sets a value that represents the distance, in points, from the left edge of the object to the left edge of column A.

New in version 0.5.0.

name

Returns or sets a String value representing the name of the object.

New in version 0.5.0.

top

Returns or sets a value that represents the distance, in points, from the top edge of the topmost shape in the shape range to the top edge of the worksheet.

New in version 0.5.0.

width

Returns or sets a value that represents the width, in points, of the object.

New in version 0.5.0.

classmethod add(sheet=None, left=0, top=0, width=355, height=211, **kwargs)

Inserts a new Chart into Excel.

Parameters:
  • sheet (str or int or xlwings.Sheet, default None) – Name or index of the Sheet or Sheet object, defaults to the active Sheet
  • left (float, default 0) – left position in points
  • top (float, default 0) – top position in points
  • width (float, default 375) – width in points
  • height (float, default 225) – height in points
Keyword Arguments:
 
  • chart_type (xlwings.ChartType member, default xlColumnClustered) – Excel chart type. E.g. xlwings.ChartType.xlLine
  • name (str, default None) – Excel chart name. Defaults to Excel standard name if not provided, e.g. ‘Chart 1’
  • source_data (Range) – e.g. Range(‘A1’).table
  • wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().
Returns:

Return type:

xlwings Chart object

chart_type

Gets and sets the chart type of a chart.

New in version 0.1.1.

set_source_data(source)

Sets the source for the chart.

Parameters:source (Range) – Range object, e.g. Range('A1')

Picture

class xlwings.Picture(*args, **kwargs)

Bases: xlwings.main.Shape

A Picture object represents an existing Excel Picture and can be instantiated with the following arguments:

Picture(1)              Picture('Sheet1', 1)                Picture(1, 1)
Picture('Picture 1')    Picture('Sheet1', 'Picture 1')      Picture(1, 'Picture 1')

The Sheet can also be provided as Sheet object:

sh = Sheet(1)
Shape(sh, 'Picture 1')

If no Worksheet is provided as first argument, it will take the Picture from the active Sheet.

Parameters:*args – Definition of Sheet (optional) and picture in the above described combinations.
Keyword Arguments:
 wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().

New in version 0.5.0.

activate()

Activates the object.

New in version 0.5.0.

delete()

Deletes the object.

New in version 0.5.0.

height

Returns or sets a value that represents the height, in points, of the object.

New in version 0.5.0.

left

Returns or sets a value that represents the distance, in points, from the left edge of the object to the left edge of column A.

New in version 0.5.0.

name

Returns or sets a String value representing the name of the object.

New in version 0.5.0.

top

Returns or sets a value that represents the distance, in points, from the top edge of the topmost shape in the shape range to the top edge of the worksheet.

New in version 0.5.0.

width

Returns or sets a value that represents the width, in points, of the object.

New in version 0.5.0.

classmethod add(filename, sheet=None, name=None, link_to_file=False, save_with_document=True, left=0, top=0, width=None, height=None, wkb=None)

Inserts a picture into Excel.

Parameters:

filename (str) – The full path to the file.

Keyword Arguments:
 
  • sheet (str or int or xlwings.Sheet, default None) – Name or index of the Sheet or xlwings.Sheet object, defaults to the active Sheet
  • name (str, default None) – Excel picture name. Defaults to Excel standard name if not provided, e.g. ‘Picture 1’
  • left (float, default 0) – Left position in points.
  • top (float, default 0) – Top position in points.
  • width (float, default None) – Width in points. If PIL/Pillow is installed, it defaults to the width of the picture. Otherwise it defaults to 100 points.
  • height (float, default None) – Height in points. If PIL/Pillow is installed, it defaults to the height of the picture. Otherwise it defaults to 100 points.
  • wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().
Returns:

Return type:

xlwings Picture object

New in version 0.5.0.

update(filename)

Replaces an existing picture with a new one, taking over the attributes of the existing picture.

Parameters:filename (str) – Path to the picture.

New in version 0.5.0.

Plot

class xlwings.Plot(figure)

Plot allows to easily display Matplotlib figures as pictures in Excel.

Parameters:figure (matplotlib.figure.Figure) – Matplotlib figure

Example

Get a matplotlib figure object:

  • via PyPlot interface:

    import matplotlib.pyplot as plt
    fig = plt.figure()
    plt.plot([1, 2, 3, 4, 5])
    
  • via object oriented interface:

    from matplotlib.figure import Figure
    fig = Figure(figsize=(8, 6))
    ax = fig.add_subplot(111)
    ax.plot([1, 2, 3, 4, 5])
    
  • via Pandas:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
    ax = df.plot(kind='bar')
    fig = ax.get_figure()
    

Then show it in Excel as picture:

plot = Plot(fig)
plot.show('Plot1')

New in version 0.5.0.

show(name, sheet=None, left=0, top=0, width=None, height=None, wkb=None)

Inserts the matplotlib figure as picture into Excel if a picture with that name doesn’t exist yet. Otherwise it replaces the picture, taking over its position and size.

Parameters:

name (str) – Name of the picture in Excel

Keyword Arguments:
 
  • sheet (str or int or xlwings.Sheet, default None) – Name or index of the Sheet or xlwings.Sheet object, defaults to the active Sheet
  • left (float, default 0) – Left position in points. Only has an effect if the picture doesn’t exist yet in Excel.
  • top (float, default 0) – Top position in points. Only has an effect if the picture doesn’t exist yet in Excel.
  • width (float, default None) – Width in points, defaults to the width of the matplotlib figure. Only has an effect if the picture doesn’t exist yet in Excel.
  • height (float, default None) – Height in points, defaults to the height of the matplotlib figure. Only has an effect if the picture doesn’t exist yet in Excel.
  • wkb (Workbook object, default Workbook.current()) – Defaults to the Workbook that was instantiated last or set via Workbook.set_current().
Returns:

  • xlwings Picture object
  • .. versionadded:: 0.5.0