Blog
How To Create Simple Bar Chart 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 = False
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 = True
ax2.HasTitle = True
ax2.AxisTitle.Text = 'Values'
ax2.AxisTitle.Font.Size = 10
ax2.TickLabels.Font.Size = 8
ax2.HasMajorGridlines = True
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('A2:B8').Select() #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlBarClustered,20,20,250,350,True)
cht=shp.Chart #
cht.ChartGroups(1).GapWidth=50
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.Volatile in the xlwings API way
The Application.Volatile method in Excel, when invoked via xlwings, marks a user-defined function (UDF) as volatile. A volatile function recalculates every time a calculation occurs in any open workbook, not just when its direct precedents change. This is essential for functions that depend on dynamic data like real-time feeds, random numbers, or the current time. In xlwings, you typically use this within a Python function decorated with @xw.func to control its recalculation behavior.
Functionality:
It ensures that the UDF recalculates with every workbook calculation cycle. This is useful for functions that need to return updated values continuously, such as those fetching live data. However, overuse can slow down performance due to excessive recalculation.
Syntax in xlwings:
In xlwings, you call Application.Volatile within a UDF by accessing the Excel application object. The method takes one optional parameter:
Volatile(True): Marks the function as volatile (default behavior if called without arguments).Volatile(False): Marks the function as non-volatile, meaning it recalculates only when its direct precedents change.
The xlwings API call format is:
xw.apps.active.api.Volatile(True) # For the active Excel application
Here, xw.apps.active refers to the active Excel application instance, and .api provides access to the underlying Excel object model. The parameter True sets volatility; use False to disable it.
Example Usage:
Consider a UDF that returns a random number, which should change on every recalculation. Without volatility, it might only update when explicitly triggered. The xlwings code below defines such a function:
import xlwings as xw
import random
@xw.func
def dynamic_random():
# Access the Excel application and set the function as volatile
xw.apps.active.api.Volatile(True)
# Return a random number between 0 and 1
return random.random()
# To use this, save the script and import it as an xlwings add-in or run it in an interactive session.
How To Create 3D Square Pyramid Column Chart 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 = False
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 = True
ax2.HasTitle = True
ax2.AxisTitle.Text = 'Values'
ax2.AxisTitle.Font.Size = 10
ax2.TickLabels.Font.Size = 8
ax2.HasMajorGridlines = True
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('A2:C8').Select() #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlPyramidCol,20,20,350,250,True)
cht=shp.Chart #
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.Union in the xlwings API way
The Application.Union method in Excel VBA is used to create a single, combined range from two or more individual ranges. This combined range object can then be used for subsequent operations, such as formatting or data manipulation, applied uniformly across all the included cells. In xlwings, this functionality is accessed through the api property of an xlwings object, which provides direct access to the underlying Excel object model. This allows Python scripts to leverage Excel’s powerful range combination logic seamlessly.
Functionality
The primary function of Union is to create a composite Range object. This is particularly useful when you need to perform the same action on multiple, non-contiguous cell blocks without having to loop through each range separately. It streamlines code and improves efficiency.
Syntax in xlwings
The syntax follows the pattern of accessing the VBA method through the xlwings api:
combined_range = xw.apps[0].api.Union(Range1, Range2, ...)
xw.apps[0].api: This accesses theApplicationobject of the first open Excel instance via xlwings..Union(): The method call.- Parameters:
Range1,Range2, …: These are two or moreRangeobjects that you want to combine. You must provide at least twoRangearguments. These ranges can refer to different worksheets or even different workbooks. - Return Value: The method returns a new
Rangeobject representing the union of all specified ranges.
Code Example
The following xlwings script demonstrates the use of Application.Union. It creates a union of three separate ranges on a sheet and then applies a yellow background fill to all cells within the combined range.
import xlwings as xw
# Connect to the active Excel instance and workbook
app = xw.apps.active
wb = app.books.active
sheet = wb.sheets['Sheet1']
# Define three separate, non-adjacent ranges
range1 = sheet.range('A1:B2')
range2 = sheet.range('D4')
range3 = sheet.range('C6:E7')
# Use the Application.Union method via the api property
# Note: We use .api on the sheet's range objects to get the native Excel Range objects for the Union method.
combined_range = app.api.Union(range1.api, range2.api, range3.api)
# Apply formatting to the entire unioned range
combined_range.Interior.Color = (255, 255, 0) # Yellow fill
# The action above fills cells A1, A2, B1, B2, D4, and the block C6:E7.
How To Create 3D Cylinder Column Chart 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 = False
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 = True
ax2.HasTitle = True
ax2.AxisTitle.Text = 'Values'
ax2.AxisTitle.Font.Size = 10
ax2.TickLabels.Font.Size = 8
ax2.HasMajorGridlines = True
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('A2:C8').Select() #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlCylinderCol,20,20,350,250,True)
cht=shp.Chart #
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.Undo in the xlwings API way
The Application.Undo method in Excel’s object model provides a way to reverse the last user-interface action performed in Excel, such as typing in a cell, formatting, or deleting data. In xlwings, this functionality is exposed through the api property, which grants direct access to the underlying Excel COM object. This allows Python scripts to mimic the “Undo” command typically executed by pressing Ctrl+Z, offering a mechanism to revert unintended changes programmatically. It is important to note that the Undo method is primarily designed for actions initiated through the Excel interface and may not work for changes made via VBA or COM automation in certain contexts. However, when called immediately after a user-style action performed via xlwings (like writing a value via the Excel interface), it can be effective.
The syntax for invoking the Undo method in xlwings is straightforward, as it does not take any parameters. The call is made through the Application object accessed from an xlwings App or Book instance. The general format is:
app.api.Undo()
Here, app refers to the xlwings App object representing the Excel application instance. The api property provides the native Excel Application COM object, and Undo() is the method call. No arguments are required or accepted. The method will reverse the last action if an undo history is available; otherwise, it may have no effect or raise an error in some scenarios.
For example, consider a scenario where a user manually types a value into a cell in an open Excel workbook, and then a script needs to undo that action. The following xlwings code demonstrates this:
import xlwings as xw
# Connect to the active Excel instance
app = xw.apps.active
# Assume a user just typed "Test" into cell A1 of the active sheet manually
# To undo that entry programmatically:
app.api.Undo()
# This will revert the change in cell A1, restoring its previous value or clearing it if it was empty.
Another example involves performing an action through xlwings that mimics user interaction, followed by an undo. Note that not all xlwings operations populate the undo stack, as many bypass the UI. However, using Range.value setter might be treated as a user action in some contexts. A more reliable approach is to simulate keystrokes or use SendKeys, but a simpler method is to leverage Excel’s Application.Run to execute a macro that performs the action, which can then be undone. Below is an illustrative code snippet that writes a value using the Excel interface via Application.Run and then undoes it:
import xlwings as xw
app = xw.apps.active
wb = app.books.active
sheet = wb.sheets[0]
# Use Application.Run to execute a VBA-like operation that can be undone
# First, define a simple VBA function in a module (this requires VBA access; alternatively, use a pre-existing macro)
# For demonstration, assume a macro named "WriteValue" exists that writes to cell B2.
# Since xlwings can run macros, we can call it and then undo.
wb.api.Run("WriteValue") # This macro might set cell B2 to "Hello"
app.api.Undo() # This should undo the macro's action, reverting cell B2
How To Create 3D Cone Column Chart 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 = False
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 = True
ax2.HasTitle = True
ax2.AxisTitle.Text = 'Values'
ax2.AxisTitle.Font.Size = 10
ax2.TickLabels.Font.Size = 8
ax2.HasMajorGridlines = True
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('A2:C8').Select() #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlConeCol,20,20,350,280,True)
cht=shp.Chart #
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.SharePointVersion in the xlwings API way
The SharePointVersion property of the Application object in Excel’s object model provides a read-only integer value that indicates the version of Microsoft SharePoint Foundation or Microsoft SharePoint Server that the current workbook is linked to, if it is stored on a SharePoint site. This property is particularly useful for developers who need to programmatically determine the SharePoint environment to implement version-specific features or compatibility checks when automating Excel through xlwings. In xlwings, this property is accessed via the api property, which exposes the underlying Excel object model.
Functionality:
The primary function is to identify the SharePoint version, enabling conditional logic in macros or scripts. For instance, certain features or methods may behave differently across SharePoint versions, and knowing the version allows for adaptive code. If the workbook is not stored on SharePoint, the property typically returns 0.
Syntax in xlwings:
The property is accessed through the Application object. In xlwings, after establishing a connection to Excel (usually via app = xw.App() or xw.Book), you can retrieve the value as follows:
import xlwings as xw
# Connect to the active Excel instance or create a new one
app = xw.apps.active # or xw.App() for a new instance
sharepoint_version = app.api.SharePointVersion
- Parameters: The
SharePointVersionproperty does not take any parameters. - Return Value: It returns an integer representing the SharePoint version. Common values include:
0: The workbook is not stored on a SharePoint site, or SharePoint is not detected.14: Corresponds to SharePoint 2010.15: Corresponds to SharePoint 2013.16: Corresponds to SharePoint 2016 or SharePoint Online (Office 365).- Other integer values may represent different or future versions.
Example Usage:
Below is a practical xlwings code example that checks the SharePoint version and performs actions based on the result. This example assumes Excel is already running with a workbook open, possibly from a SharePoint location.
import xlwings as xw
def check_sharepoint_version():
# Get the active Excel application
app = xw.apps.active
# Retrieve the SharePoint version
version = app.api.SharePointVersion
# Display or use the version information
if version == 0:
print("This workbook is not stored on SharePoint.")
elif version == 14:
print("SharePoint 2010 detected. Implement compatibility for this version.")
# Add version-specific code here, e.g., adjust data connection settings
elif version == 15:
print("SharePoint 2013 detected. Features for this version are available.")
elif version == 16:
print("SharePoint 2016 or SharePoint Online detected. Use modern APIs.")
else:
print(f"Unknown SharePoint version: {version}. Check for updates.")
# You can also use the value in conditional logic for further automation
if version >= 16:
# Example: Enable newer SharePoint integration features
print("Proceeding with advanced SharePoint functionalities.")
return version
# Run the function
if __name__ == "__main__":
sharepoint_ver = check_sharepoint_version()
print(f"SharePoint Version Code: {sharepoint_ver}")
How To Create 3D Column Chart 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 = False
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 = True
ax2.HasTitle = True
ax2.AxisTitle.Text = 'Values'
ax2.AxisTitle.Font.Size = 10
ax2.TickLabels.Font.Size = 8
ax2.HasMajorGridlines = True
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('A2:D7').Select() #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xl3DColumn,20,20,350,250,True)
cht=shp.Chart #
#cht.ChartGroups(1).GapWidth=50
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.SendKeys in the xlwings API way
The SendKeys member of the Application object in Excel is a powerful method for simulating keystrokes directly to the active application window, typically Excel itself. In xlwings, this functionality is exposed through the api property, allowing you to programmatically send key combinations that would normally be entered manually. This can be used to automate tasks like opening menus, triggering shortcuts, or interacting with dialog boxes, especially when other programmatic methods are limited. It’s particularly useful for legacy automation scenarios where UI interaction is required.
Syntax in xlwings:
The syntax follows the Excel Object Model via the xlwings api:
app.api.SendKeys(Keys, Wait)
- Keys: A string expression specifying the keystrokes to send. Use codes like
"{F5}"for function keys,"^c"for Ctrl+C, or"%f"for Alt+f. Special keys are enclosed in braces (e.g.,"{ENTER}","{TAB}"). To send literal characters, simply type them. - Wait: Optional Boolean. If
True, Excel waits for the keys to be processed before continuing. IfFalseor omitted, the macro continues immediately without waiting. Default isFalse.
Key Code Examples:
| Key Combination | Code String |
|---|---|
| Enter | "{ENTER}" |
| Ctrl+A | "^a" |
| Alt+F4 | "%{F4}" |
| Shift+Tab | "+{TAB}" |
| Page Down | "{PGDN}" |
Examples in xlwings:
- Activate the Find Dialog (Ctrl+F):
import xlwings as xw
app = xw.apps.active # Get the active Excel application
app.api.SendKeys("^f") # Send Ctrl+F to open Find
- Refresh All Data Connections (Alt+F5):
app.api.SendKeys("%{F5}", Wait=True) # Alt+F5 and wait for completion
- Navigate and Select a Cell Range:
app.api.SendKeys("{F5}") # Open Go To dialog
app.api.SendKeys("A1:D10{ENTER}") # Type range and press Enter
- Close the Active Workbook with Save Prompt (Alt+F, then C):
app.api.SendKeys("%fc") # Alt+F to open File menu, then C for Close
# Note: This may interact with save dialogs; handle with caution.