Archive

How To Set Plot Area Using xlwings?

Method

The chart area is the rectangular area that contains the entire chart, while the plot area is the rectangular area defined by the two axes. In Excel, the chart area is represented by the `ChartArea` object, and the plot area is represented by the `PlotArea` object. You can access these areas using the `ChartArea` and `PlotArea` properties of the `Chart` object.

By continuously referencing the `ChartArea` and `PlotArea` objects’ `Format.Fill` property, you can set the fill properties of both areas, such as their color, transparency, gradient fills, pattern fills, picture fills, texture fills, etc.

Using the `Format.Shadow` property of the `ChartArea` and `PlotArea` objects, you can set additional shadow properties for these areas. The `Format.Shadow` property returns a `ShadowFormat` object with the following main properties:

– **Visible**: Determines whether the shadow is visible.

– **Blur**: Gets or sets the blur radius of the shadow.

– **Transparency**: Gets or sets the transparency of the shadow (from 0.0 for opaque to 1.0 for fully transparent).

– **OffsetX**: Gets or sets the horizontal offset of the shadow in points. Positive values shift the shadow to the right, while negative values shift it to the left.

– **OffsetY**: Gets or sets the vertical offset of the shadow in points. Positive values shift the shadow downward, while negative values shift it upward.

sht.api.Range(‘A1:B7’).Select()

cht=sht.api.Shapes.AddChart().Chart

cha=cht.ChartArea    #Chart Area

cha.Format.Fill.ForeColor.RGB=xw.utils.rgb_to_int((155,255,0))

cha.Shadow=True    #Plot area shows shadow

pla=cht.PlotArea    #Plot area

pla.Format.Fill.UserPicture(root+r’/picpy2.jpg’)    #Picture fill

cht.SeriesCollection(1).Format.Fill.ForeColor.RGB=xw.utils.rgb_to_int((255,255,0))

cht.Axes(2).HasMajorGridlines=False

cha.Shadow=False

pla.Format.Shadow.Visible=True    #Plot area shows shadow

pla.Format.Shadow.OffsetX=3    #Horizontal offset of the shadow

pla.Format.Shadow.OffsetY=3    #Vertical offset of the shadow

 

Example

import xlwings as xw
import os

def set_style(cht):
    cht.ChartArea.Format.Line.Visible=False
    cht.PlotArea.Format.Fill.Visible=True
    cht.PlotArea.Format.Line.Visible=True
    cht.PlotArea.Format.Line.ForeColor.RGB=xw.utils.rgb_to_int((200,200,200))
    #cht.PlotArea.Format.Line.ForeColor.ObjectThemeColor=msoThemeColorText1
    ax1=cht.Axes(1)
    ax2=cht.Axes(2)
    ax1.HasTitle=True
    ax1.AxisTitle.Text='Categories'
    ax1.AxisTitle.Font.Size=10
    ax1.TickLabels.Font.Size=8
    #ax1.TickLabels.NumberFormat='0.00'
    ax1.HasMajorGridlines=False
    ax2.HasTitle=True
    ax2.AxisTitle.Text='Values'
    ax2.AxisTitle.Font.Size=10
    ax2.TickLabels.Font.Size=8
    ax2.HasMajorGridlines=False
    cht.HasTitle=True
    #cht.ChartTitle.Caption='Plot'
    #cht.ChartTitle.Font.Size=12

root=os.getcwd()
app=xw.App(visible=True, add_book=False)
wb=app.books.open(root+r'/data.xlsx',read_only=False)
sht=wb.sheets('Sheet1')

sht.api.Range('A1:B7').Select()    #
cht=sht.api.Shapes.AddChart2(-1, \
          xw.constants.ChartType.xlColumnClustered,20,20,350,250,True).Chart
cht.PlotArea.Format.Fill.ForeColor.RGB=xw.utils.rgb_to_int((255,255,26))
cht.PlotArea.Format.Fill.OneColorGradient(1,1,1)    #msoGradientHorizontal
      
set_style(cht)

cht.Export(root+'/cht.jpg')
cht.Export(root+'/cht.svg')
cht.ExportAsFixedFormat(0,root+'/cht.pdf')

#wb.save()
#app.kill()

How to use Application.ExecuteExcel4Macro in the xlwings API way

The ExecuteExcel4Macro member of the Application object in Excel’s object model provides a way to run Excel 4.0 macro functions, which are legacy commands from older versions of Excel. While modern Excel primarily uses VBA, these functions can still be useful for specific tasks that are not directly supported by newer APIs, such as certain financial or engineering calculations. In xlwings, this functionality is accessed through the api property, which exposes the underlying Excel object model, allowing Python scripts to interact with Excel in a manner similar to VBA.

The syntax for calling ExecuteExcel4Macro via xlwings is straightforward. First, you need to obtain the Application object from an xlwings App or Book instance. Then, you can invoke the method. The method takes a single string argument, String, which represents the Excel 4.0 macro function you want to execute. This string should be formatted exactly as it would be in Excel 4.0, including any required arguments. For example, a common function is GET.CELL, which retrieves information about a cell. The parameter is provided as a plain string, and you must ensure it is correctly quoted and concatenated if variables are involved. There is no return value specification in the syntax itself; the output depends on the macro function called.

Here is a basic example that demonstrates how to use ExecuteExcel4Macro with xlwings to get the full path of the active workbook, using the Excel 4.0 function GET.DOCUMENT(1):

import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active

# Execute the Excel 4.0 macro function to get the full path
full_path = app.api.ExecuteExcel4Macro("GET.DOCUMENT(1)")

print(f"Full path of active workbook: {full_path}")

Another example involves retrieving a specific cell’s value using GET.CELL. This can be useful for getting properties like the cell’s format or formula. In this case, you need to construct a reference string:

import xlwings as xw

# Connect to the active workbook and sheet
wb = xw.books.active
sheet = wb.sheets.active

# Define the cell address, e.g., A1
cell_address = "A1"

# Execute GET.CELL(6, A1) to get the formula in the cell (6 is the type_num for formula)
# Note: The reference must be provided as an R1C1-style reference or a named range
formula_result = wb.app.api.ExecuteExcel4Macro(f'GET.CELL(6, {cell_address})')

print(f"Formula in {cell_address}: {formula_result}")

How To Set Chart Title Using xlwings?

Example

Code

import xlwings as xw
import os

def set_style(cht):
    cht.ChartArea.Format.Line.Visible=False
    cht.PlotArea.Format.Fill.Visible=False
    cht.PlotArea.Format.Line.Visible=True
    cht.PlotArea.Format.Line.ForeColor.RGB=xw.utils.rgb_to_int((200,200,200))
    #cht.PlotArea.Format.Line.ForeColor.ObjectThemeColor=msoThemeColorText1
    ax1=cht.Axes(1)
    ax2=cht.Axes(2)
    ax1.HasTitle=True
    ax1.AxisTitle.Text='Categories'
    ax1.AxisTitle.Font.Size=10
    ax1.TickLabels.Font.Size=8
    #ax1.TickLabels.NumberFormat='0.00'
    ax1.HasMajorGridlines=False
    ax2.HasTitle=True
    ax2.AxisTitle.Text='Values'
    ax2.AxisTitle.Font.Size=10
    ax2.TickLabels.Font.Size=8
    ax2.HasMajorGridlines=False
    cht.HasTitle=True
    #cht.ChartTitle.Caption='Plot'
    #cht.ChartTitle.Font.Size=12

root=os.getcwd()
app=xw.App(visible=True,add_book=False)
wb=app.books.open(root+r'/data.xlsx',read_only=False)
sht=wb.sheets('Sheet1')

sht.api.Range('A1:B7').Select()    #
cht=sht.api.Shapes.AddChart2(-1,\
          xw.constants.ChartType.xlColumnClustered,20,20,350,250,True).Chart
cht.HasTitle=True
cht.ChartTitle.Caption='Chart Title'
cht.ChartTitle.Characters.Font.Name='Times New Roman'
cht.ChartTitle.Characters.Font.Size=16
cht.ChartTitle.Characters.Font.Bold=True
cht.ChartTitle.Characters.Font.Color=xw.utils.rgb_to_int((255,0,0))
      
set_style(cht)

cht.Export(root+'/cht.jpg')
cht.Export(root+'/cht.svg')
cht.ExportAsFixedFormat(0,root+'/cht.pdf')

#wb.save()
#app.kill()

How to use Application.Evaluate in the xlwings API way

The Application.Evaluate method in Excel is a powerful tool for converting a Microsoft Excel name or a formula string into an actual value or a reference object. In xlwings, this functionality is exposed through the api property of an App or Book object, allowing you to leverage Excel’s calculation engine directly from Python. This is particularly useful for evaluating complex formulas that are easier to express in Excel’s native syntax than to replicate in Python code, or for retrieving the value of a defined name.

The syntax in xlwings follows the pattern of accessing the underlying Excel object model. To call Evaluate, you first obtain the Excel Application object via the api property. The method takes a single string argument, which is the name or formula to be evaluated.

Syntax:

app.api.Evaluate(Name)
  • app: This is your xlwings App object (e.g., xlwings.App() or xw.apps.active).
  • .api: This property provides direct access to the pywin32 or appscript COM object, enabling calls to the raw Excel VBA object model.
  • .Evaluate: The method being called.
  • Name (String, Required): A formula, a defined name, or a reference (as a string) that you want Excel to evaluate. This must be provided in the locale of the Excel application or in A1-style notation. For example, "SUM(A1:B10)", "MyNamedRange", or "Sheet1!$C$5".

The method returns the result of the evaluated formula. This can be a simple data type (like a number, string, or boolean), an xlwings.Range object (if the name evaluates to a range reference), or an error.

Code Examples:

  1. Evaluating a Mathematical Formula:
    This calculates a formula string and returns the numeric result.
import xlwings as xw

app = xw.App(visible=False)
wb = app.books.add()
# Place values in cells
wb.sheets[0].range('A1').value = 10
wb.sheets[0].range('A2').value = 20

# Use Evaluate to compute the sum
result = app.api.Evaluate("SUM(A1:A2)")
print(result) # Output: 30.0
wb.close()
app.quit()
  1. Evaluating a Defined Name:
    This retrieves the value or reference associated with a name defined in the workbook.
import xlwings as xw

app = xw.App(visible=False)
wb = app.books.add()
# Define a name for a range
wb.api.Names.Add(Name="MyData", RefersTo="=Sheet1!$A$1:$A$5")
# Put values into the named range
wb.sheets['Sheet1'].range('A1:A5').value = [[1], [2], [3], [4], [5]]

# Evaluate the defined name to get its value (the array)
name_result = app.api.Evaluate("MyData")
print(list(name_result)) # Output: [1.0, 2.0, 3.0, 4.0, 5.0]
wb.close()
app.quit()
  1. Evaluating a Formula that Returns a Range Object:
    This is useful for obtaining an xlwings Range object from a string reference.
import xlwings as xw

app = xw.App(visible=True)
wb = app.books.add()
ws = wb.sheets[0]
ws.range('B2').value = "Hello World"

# Evaluate returns a Range COM object, which xlwings wraps.
# The xlwings Range constructor can handle this COM object.
range_ref = app.api.Evaluate("Sheet1!B2")
xl_range = xw.Range(range_ref) # Wrap it in xlwings Range
print(xl_range.value) # Output: Hello World
print(xl_range.address) # Output: $B$2
# wb.close() and app.quit() omitted for an interactive example.

How To Use SetElement Method Using xlwings?

Method

The `SetElement` method of the `Chart` object allows you to set chart elements for the specified chart. The method has one parameter that provides options for setting. The possible values of the parameter are shown in the table below.

Name

Value

Description

msoElementChartFloorNone

1200

Do not display chart floor

msoElementChartFloorShow

1201

Display chart floor

msoElementChartTitleAboveChart

2

Display title above the chart

msoElementChartTitleCenteredOverlay

1

Display title centered as overlay

msoElementChartTitleNone

0

Do not display chart title

msoElementChartWallNone

1100

Do not display chart background wall

msoElementChartWallShow

1101

Display chart background wall

msoElementDataLabelBestFit

210

Use best fit data labels

msoElementDataLabelBottom

209

Display data labels at the bottom

msoElementDataLabelCallout

211

Display data labels as callouts

msoElementDataLabelCenter

202

Centered data labels

msoElementDataLabelInsideBase

204

Display data labels inside the base

msoElementDataLabelInsideEnd

203

Display data labels inside the end

msoElementDataLabelLeft

206

Display data labels on the left

msoElementDataLabelNone

200

Do not display data labels

msoElementDataLabelOutSideEnd

205

Display data labels outside the end

msoElementDataLabelRight

207

Display data labels on the right

msoElementDataLabelShow

201

Display data labels

msoElementDataLabelTop

208

Display data labels at the top

msoElementDataTableNone

500

Do not display data table

msoElementDataTableShow

501

Display data table

msoElementDataTableWithLegendKeys

502

Display data table with legend keys

msoElementErrorBarNone

700

Do not display error bars

msoElementErrorBarPercentage

702

Display percentage error bars

msoElementErrorBarStandardDeviation

703

Display standard deviation error bars

msoElementErrorBarStandardError

701

Display standard error error bars

msoElementLegendBottom

104

Display legend at the bottom

msoElementLegendLeft

103

Display legend on the left

msoElementLegendLeftOverlay

106

Overlay legend on the left

msoElementLegendNone

100

Do not display legend

msoElementLegendRight

101

Display legend on the right

msoElementLegendRightOverlay

105

Overlay legend on the right

msoElementLegendTop

102

Display legend at the top

msoElementLineDropHiLoLine

804

Display drop line and high/low lines

msoElementLineDropLine

801

Display drop line

msoElementLineHiLoLine

802

Display high/low line

msoElementLineNone

800

Do not display lines

msoElementLineSeriesLine

803

Display series lines

msoElementPlotAreaNone

1000

Do not display plot area

msoElementPlotAreaShow

1001

Display plot area

How to use Application.DoubleClick in the xlwings API way

In the Excel object model, the Application.DoubleClick method is a powerful feature that simulates a double-click action on the active cell in Excel. This action can trigger various Excel behaviors, such as entering cell edit mode, opening a cell for formula editing, or activating specific cell features like data validation lists. In xlwings, this functionality is accessible through the api property, which provides direct access to the underlying Excel COM object. This allows Python scripts to automate user interactions that typically require manual double-clicks, enhancing automation workflows in data processing and analysis.

The syntax for using DoubleClick in xlwings is straightforward, as it is called as a method without any parameters. Since it operates on the active cell, it requires that a cell is selected or active in the Excel application. In xlwings, you typically access this through the Application object, which represents the Excel instance. The method is invoked as follows:

app.api.DoubleClick()

Here, app refers to the xlwings App instance connected to Excel. The api property exposes the native Excel COM interface, allowing direct calls to methods like DoubleClick. This method does not take any arguments; it simply performs the double-click action on whatever cell is currently active in Excel. It is important to note that the effectiveness of this method depends on the context—for example, if the active cell contains a formula, double-clicking might place the cursor in the formula bar for editing, while in a cell with data validation, it might open a drop-down list.

To use Application.DoubleClick in xlwings, you must first ensure an Excel application is running and a workbook is open. Below are practical code examples demonstrating its usage:

Example 1: Basic double-click to edit a cell. This example opens Excel, selects a specific cell, and simulates a double-click to enter edit mode.

import xlwings as xw

# Connect to the active Excel instance or start a new one
app = xw.apps.active if xw.apps.active else xw.App()
wb = app.books.active if app.books else app.books.add()
ws = wb.sheets.active

# Select cell A1 and activate it
ws.range('A1').select()
app.api.DoubleClick() # Simulate double-click on A1
# This may allow editing of the cell content in Excel

Example 2: Using double-click in a loop to process multiple cells. This can be useful for automating tasks like checking data validation or triggering macros tied to cell events.

import xlwings as xw

app = xw.apps.active
if app:
    ws = app.books.active.sheets.active
    for cell in ws.range('B1:B5'):
        cell.select() # Make each cell active
        app.api.DoubleClick() # Double-click to interact with each cell
        # Add a pause or other operations as needed, e.g., app.wait(1)

Example 3: Combining with other xlwings features to log actions. This example double-clicks on a cell and then updates another cell with a timestamp.

import xlwings as xw
from datetime import datetime

app = xw.apps.active
if app:
    ws = app.books.active.sheets.active
    target_cell = ws.range('C3')
    target_cell.select()
    app.api.DoubleClick() # Trigger double-click on C3
    # Record the action in cell D3
    ws.range('D3').value = f'Double-clicked at {datetime.now().strftime("%H:%M:%S")}'

How to use Application.DisplayXMLSourcePane in the xlwings API way

The DisplayXMLSourcePane member of the Application object in Excel is a property that controls the visibility of the XML Source task pane. This pane is used when working with XML maps in Excel, allowing users to view and manage XML elements mapped to cells or ranges in a workbook. It is particularly useful for developers and advanced users who handle XML data integration, enabling them to see the structure of XML data and its mappings directly within the Excel interface. In xlwings, this property can be accessed and manipulated to programmatically show or hide the XML Source pane, enhancing automation in workflows involving XML data processing.

In terms of syntax, the DisplayXMLSourcePane property is accessed through the Application object in xlwings. The xlwings API provides a Pythonic way to interact with Excel’s object model. The property is a boolean value, where True indicates that the XML Source pane is visible, and False indicates it is hidden. The xlwings call format is straightforward: you reference the Application object and set or get the DisplayXMLSourcePane property. For example, to retrieve the current state, you use app.api.DisplayXMLSourcePane, and to change it, you assign a boolean value like app.api.DisplayXMLSourcePane = True. Note that in xlwings, the api attribute is used to access the underlying Excel object model properties and methods directly, ensuring compatibility with Excel’s native functionality.

Here are some code examples demonstrating the use of DisplayXMLSourcePane with xlwings. First, ensure you have xlwings installed and an Excel instance running. You can use the following snippets in a Python script or interactive environment. In the first example, we check if the XML Source pane is currently visible and print its status:

import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active

# Get the current state of the DisplayXMLSourcePane property
is_visible = app.api.DisplayXMLSourcePane
print(f"The XML Source pane is visible: {is_visible}")

To show the XML Source pane, set the property to True:

# Show the XML Source pane
app.api.DisplayXMLSourcePane = True
print("XML Source pane is now visible.")

To hide it, set the property to False:

# Hide the XML Source pane
app.api.DisplayXMLSourcePane = False
print("XML Source pane is now hidden.")

You can also toggle the visibility based on its current state. This is useful in automation scripts where you might need to ensure the pane is visible before performing XML-related operations:

# Toggle the visibility of the XML Source pane
current_state = app.api.DisplayXMLSourcePane
app.api.DisplayXMLSourcePane = not current_state
print(f"Toggled XML Source pane visibility to: {not current_state}")

How To Set Axis Reversing Using xlwings?

Method

axs.ReversePlotOrder=True

axs2.ReversePlotOrder=True

Example

Code

import xlwings as xw
import os

root=os.getcwd()
app=xw.App(visible=True,add_book=False)
wb=app.books.open(root+r'/data2.xlsx',read_only=False)
sht=wb.sheets('Sheet1')

sht.api.Range('A1:B7').Select()    #
shp=sht.api.Shapes.AddChart()    #
shp.Left=20
cht=shp.Chart
axs=cht.Axes(1)    #
axs.Border.ColorIndex=3    #
axs.Border.Weight=3    #
axs2=cht.Axes(2)    #
axs.ReversePlotOrder=True
axs2.ReversePlotOrder=True

#wb.save()
#app.kill()

How to use Application.DeleteCustomList in the xlwings API way

The DeleteCustomList member of the Application object in Excel VBA is used to remove a previously defined custom autofill or sort list. In xlwings, which provides a Pythonic interface to Excel’s object model, this functionality can be accessed through the api property of an App or Book object, which exposes the underlying VBA object model. This is particularly useful for managing custom lists programmatically, such as cleaning up temporary lists or resetting configurations in automated Excel tasks.

Functionality
The primary purpose of DeleteCustomList is to delete a custom list that has been added to Excel. Custom lists are often used for custom sorting orders or to define autofill sequences (e.g., a list of department names or project stages). Deleting a list can help maintain a clean Excel environment, especially when lists are created dynamically during a script’s execution and are no longer needed afterward.

Syntax in xlwings
In xlwings, you call this method via the Application object obtained from an xlwings App instance. The syntax is:

app.api.DeleteCustomList(ListNum)
  • app: This is an xlwings App object, representing the Excel application.
  • api: This property provides direct access to the VBA Application object.
  • DeleteCustomList: The method being called.
  • ListNum: A required parameter of type Integer. It specifies the index number of the custom list to delete. The index corresponds to the position of the list in Excel’s custom lists collection, where custom lists are numbered sequentially starting from 1. Note that Excel’s built-in lists (like days and months) cannot be deleted and are not included in this count; the indexing applies only to user-defined custom lists.

To determine the correct ListNum for a specific list, you may need to retrieve it from Excel’s list collection. This can be done by using the GetCustomListNum method or by iterating through custom lists if you know the list’s contents. However, DeleteCustomList itself does not identify lists by name; it requires the numerical index.

Code Example
Below is an example demonstrating how to use DeleteCustomList in xlwings. This script adds a custom list, confirms its addition, and then deletes it. Note that error handling is important because attempting to delete a non-existent list or an out-of-range index will raise a com error.

import xlwings as xw

# Start or connect to Excel application
app = xw.App(visible=False) # Set visible=True to see Excel interface

try:
    # First, add a custom list for demonstration
    custom_list = ["North", "South", "East", "West"]
    app.api.AddCustomList(ListArray=custom_list)
    print("Custom list added successfully.")

    # Assume we want to delete the most recently added list.
    # In a real scenario, you might need to find the index dynamically.
    # Here, we use index 1, assuming it's the first user-defined list.
    # Note: This might fail if other custom lists exist.
    list_num = 1 # Index for the custom list to delete
    app.api.DeleteCustomList(ListNum=list_num)
    print(f"Custom list at index {list_num} deleted.")

except Exception as e:
    print(f"An error occurred: {e}")

finally:
    # Close Excel
    app.quit()

In this example, list_num is hard-coded as 1 for simplicity. In practice, to reliably delete a specific list, you might first use GetCustomListNum to find its index based on the list array, or maintain a record of list indices when creating them. The AddCustomList method returns the index of the newly created list, which can be stored for later deletion. For instance:

# When adding a list, store the returned index
new_list_index = app.api.AddCustomList(ListArray=custom_list)
# Later, delete using the stored index
app.api.DeleteCustomList(ListNum=new_list_index)

How To Set Crosses Using xlwings?

Method

Use the **AxisBetweenCategories** property of the **Axis** object to set the intersection point between the value axis and the category axis. If the value is `True`, the intersection occurs in the middle of the categories; if it is `False`, the intersection occurs at the middle point of the categories.

 

The **Crosses** property of the **Axis** object returns or sets the point at which the axis intersects with another axis. The possible values for this property are as follows:

 

Name

Value

Description

xlAxisCrossesAutomatic

-4105

Automatically set by Excel

xlAxisCrossesCustom

-4114

Set by **CrossesAt** property

xlAxisCrossesMaximum

2

Axis crosses at maximum value

xlAxisCrossesMinimum

4

Axis crosses at minimum value

 

sht.api.Range(‘A1:B7’).Select()

cht=sht.api.Shapes.AddChart().Chart

axs2=cht.Axes(2)

axs2.Crosses=2

#axs2.Crosses=-4114

#axs2.CrossesAt=50

 

Example

Code

import xlwings as xw
import os

root=os.getcwd()
app=xw.App(visible=True,add_book=False)
wb=app.books.open(root+r'/data2.xlsx',read_only=False)
sht=wb.sheets('Sheet1')

sht.api.Range('A1:B7').Select()    #
shp=sht.api.Shapes.AddChart()    #
shp.Left=20
cht=shp.Chart
axs=cht.Axes(1)    #
axs.Border.ColorIndex=3    #
axs.Border.Weight=3    #
axs2=cht.Axes(2)    #
axs.Crosses=xw.constants.AxisCrosses.xlAxisCrossesMaximum
axs2.CrossesAt=10

#wb.save()
#app.kill()