Archive

How To Create Stacked 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 = 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 = 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:C11').Select()  #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlColumnStacked,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.RecordMacro in the xlwings API way

The Application.RecordMacro method in Excel’s object model is a powerful feature for automating the recording of a sequence of actions into a VBA macro. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying COM object, allowing you to leverage Excel’s native methods. This is particularly useful for developers who need to programmatically initiate macro recording, such as in testing scenarios or when building tools that assist users in creating macros without manually clicking the record button.

Functionality:
The primary purpose of RecordMacro is to start the macro recorder in Excel. When invoked, it begins capturing user interactions (like cell edits, formatting changes, or menu selections) and translates them into VBA code. This recorded code can then be saved to a module for later execution. In an automation context, using RecordMacro via xlwings enables scripts to trigger this recording process seamlessly, integrating macro generation into larger Python-based workflows.

Syntax in xlwings:
The method is called through the Application object. In xlwings, you typically access this via the app object representing an Excel instance. The syntax is:

app.api.RecordMacro(BasicCode, XlmCode)
  • BasicCode (Optional, Variant): A string that specifies the VBA code to be used as the macro. If provided, Excel will use this code directly instead of recording actions. If omitted, Excel starts recording interactively.
  • XlmCode (Optional, Variant): A string that specifies Excel 4.0 macro language (XLM) code. This is rarely used in modern contexts and is primarily for backward compatibility. It can be omitted.

Both parameters are optional. If neither is supplied, Excel begins recording a macro normally, prompting the user to save it later. If BasicCode is provided, Excel writes that code to a new module without interactive recording.

Code Examples:
Below are practical examples demonstrating how to use RecordMacro with xlwings.

  1. Starting Interactive Macro Recording:
    This example opens Excel and initiates the macro recorder, which will capture subsequent manual actions.
import xlwings as xw

# Connect to a running Excel instance or start a new one
app = xw.apps.active or xw.App()

# Start recording a macro interactively
app.api.RecordMacro()

# At this point, perform actions in Excel (e.g., type in a cell)
# After completing actions, stop recording via Excel's UI or programmatically
# Note: Stopping recording programmatically isn't direct via RecordMacro; it requires sending keystrokes or using SendKeys.
  1. Providing Predefined VBA Code:
    Instead of interactive recording, you can supply VBA code directly. This example creates a macro that inserts a timestamp.
import xlwings as xw

app = xw.apps.active or xw.App()
vba_code = """
Sub InsertTimestamp()
ActiveCell.Value = Now()
End Sub
"""

# Record the macro using the provided code
app.api.RecordMacro(BasicCode=vba_code)

# This will create a macro named "InsertTimestamp" in a new module
# Save the workbook to retain the macro
app.books.active.save()
  1. Integrating with User Workflows:
    In a tool that guides users, you might combine RecordMacro with other xlwings features. For instance, after preparing a worksheet, you could start recording for custom user actions.
import xlwings as xw

app = xw.App(visible=True)
wb = app.books.add()
ws = wb.sheets[0]
ws.range("A1").value = "Start recording your macro below:"

# Prompt user and begin recording
input("Press Enter to start macro recording...")
app.api.RecordMacro()

print("Recording started. Perform actions in Excel, then stop recording manually.")

Important Notes:

  • When using RecordMacro without parameters, the recording must be stopped manually by the user (e.g., clicking the stop button in Excel). Automating the stop process is complex and may require simulating keystrokes via SendKeys or using Windows API calls, which is beyond xlwings’ core functionality.
  • The method is part of Excel’s COM interface; thus, it requires Excel to be running and may have limitations in headless environments. Ensure Excel is visible (visible=True) for interactive recording.
  • For advanced automation, consider generating VBA code directly via xlwings’ vba module or using Python to write to modules, as this offers more control than relying on recording.

How To Create Clustered 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 = 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 = 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:C7').Select()  #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlColumnClustered,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.Quit in the xlwings API way

The Application.Quit method in Excel’s object model is a critical command for programmatically closing the Excel application itself. When automating tasks using xlwings, a Python library that interacts with Excel via its COM API, the Quit method provides a clean and controlled way to terminate the Excel process, especially after a script has completed its operations. This is essential for resource management, ensuring that no hidden Excel instances remain running in the background, which could consume memory and system resources. In xlwings, this method is accessed through the App object, which represents the Excel application.

Functionality:
The primary function of Quit is to close the Microsoft Excel application. It is analogous to manually clicking the close button (the “X”) on the Excel window or selecting “Exit” from the File menu. When invoked, it prompts Excel to close all open workbooks. If there are any unsaved changes in any open workbook, Excel will typically display a dialog box asking the user to save, discard changes, or cancel the quit operation, unless this default behavior is overridden by other settings (like DisplayAlerts being set to False).

Syntax in xlwings:
The xlwings API provides a Pythonic way to call this method. The general syntax is:

app.quit()

Here, app is an instance of the xlwings.App class, representing a running Excel application. The quit() method does not take any parameters in its xlwings implementation. It’s a direct wrapper around the underlying COM Quit method.

Important Considerations and Parameters:
While the xlwings app.quit() method itself has no arguments, the behavior upon quitting is influenced by the state of Excel’s DisplayAlerts property and the Saved status of workbooks. To quit without being prompted to save, you can set DisplayAlerts to False before calling quit(). However, this will discard any unsaved changes without warning.

Related Settingxlwings AccessEffect on Quit
DisplayAlertsapp.display_alerts = FalseSuppresses save prompts; unsaved data is lost.
Workbook Saved Propertywb.saved = TrueMarks a workbook as saved, preventing a prompt for that specific book.

Code Examples:

  1. Basic Quit: This example starts Excel, creates a new workbook, and then closes the application. If the workbook has not been saved, a prompt will appear.
import xlwings as xw
# Start Excel and create a new workbook
app = xw.App(visible=True)
wb = app.books.add()
# ... perform some operations ...
# Quit Excel (may show save prompt)
app.quit()
  1. Quit Without Save Prompts: This example demonstrates how to force Excel to close immediately, discarding any unsaved changes by turning off alerts.
import xlwings as xw
app = xw.App(visible=True)
wb = app.books.add()
wb.sheets[0].range('A1').value = "Unsaved Data"
# Disable alert dialogs
app.display_alerts = False
# Quit Excel; no prompt will appear, and changes are lost
app.quit()
  1. Quit After Saving: A more controlled approach is to save workbooks explicitly before quitting.
import xlwings as xw
import os
app = xw.App(visible=True)
wb = app.books.add()
wb.sheets[0].range('A1').value = "Important Data"
# Save the workbook to a specific path
file_path = os.path.join(os.getcwd(), 'report.xlsx')
wb.save(file_path)
# Now it's safe to quit without prompts
app.quit()

How To Create Picture Filled Simple 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 = 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 = 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:B9').Select()  #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlColumnClustered,20,20,350,250,True)
cht=shp.Chart  #
cht.ChartGroups(1).GapWidth=40
cht.SeriesCollection(1).Format.Fill.UserPicture('D:/pic.jpg')
cht.SeriesCollection(1).Format.Line.ForeColor.RGB=xw.utils.rgb_to_int((0,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.OnUndo in the xlwings API way

The Application.OnUndo method in Excel’s object model is a powerful feature that allows developers to customize the text displayed on the Undo button in the Quick Access Toolbar and specify a macro to run when that Undo command is executed. This is particularly useful for creating custom undo sequences for complex operations that involve multiple steps or external data changes, going beyond Excel’s built-in undo stack. In xlwings, which provides a Pythonic interface to automate Excel, you can access this functionality through the Application object’s api property, which exposes the underlying COM object, enabling you to call VBA-compatible methods directly.

Functionality:
The primary function of OnUndo is to assign a custom undo procedure. When a user clicks the Undo button after your code has set this property, Excel will run the specified macro instead of performing a standard undo. This allows for tailored reversal of actions that might not be captured by Excel’s native undo history, such as modifications to external databases, specific formatting sequences, or multi-sheet operations. It essentially overrides the default undo behavior for the next undo action only.

Syntax in xlwings:
In xlwings, you interact with the OnUndo method via the COM API. The general syntax is:

app.api.OnUndo(Text, Procedure)
  • Text: A required String argument. This is the text that will appear on the Undo button (e.g., “Undo Custom Import”). It should clearly describe the action to be reversed.
  • Procedure: A required String argument. This is the name of the macro (a VBA subroutine) that Excel will execute when the Undo button is clicked. The macro must be stored in a code module of the workbook.

Important Notes on Parameters:

  1. The Procedure must be a macro accessible in the workbook. In an xlwings context, you can write UDFs (User Defined Functions) or macros in VBA modules that are called from Python, but the OnUndo method itself calls VBA code. Therefore, you typically need a VBA macro in place.
  2. The custom undo text remains active only for the next undo operation. After the user clicks Undo or performs another action, Excel reverts to its default undo text and behavior.
  3. This method does not work for undoing events that occur after the workbook is closed; it is session-specific.

Example Usage with xlwings:
Suppose you have a Python script using xlwings that imports data and performs a complex transformation. You want to provide an undo option that reverts this import. First, ensure you have a VBA macro named UndoCustomImport in a module of your workbook. This macro might clear the imported range or restore original values.

Here is a sample xlwings code snippet:

import xlwings as xw

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

# Connect to the specific workbook
wb = app.books['MyWorkbook.xlsm']

# Run your custom data import and processing code
# ... (e.g., clear a range, write new data from a DataFrame)

# Set the custom Undo text and procedure
app.api.OnUndo("Undo Data Import", "UndoCustomImport")

# Inform the user
print("Data import completed. You can undo this action using 'Undo Data Import' in Excel.")

How To Create Pattern Filled Simple 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 = 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 = 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:B9').Select()  #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlColumnClustered,20,20,350,250,True)
cht=shp.Chart  #
cht.ChartGroups(1).GapWidth=40
cht.SeriesCollection(1).Format.Fill.Patterned(26)
cht.SeriesCollection(1).Format.Line.ForeColor.RGB=xw.utils.rgb_to_int((0,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.OnTime in the xlwings API way

The OnTime method in Excel’s Application object is a powerful feature for scheduling the execution of a procedure at a specific future time or after a specific time interval. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model. This allows for the automation of repetitive tasks, data refreshes, or timed notifications without user intervention, effectively enabling time-driven macros within a Python-controlled Excel environment.

Functionality:
The primary function is to run a specified VBA macro (procedure) at a predetermined time. It can be used for one-time execution or to set up recurring schedules. While xlwings itself runs Python code, OnTime schedules the execution of VBA macros stored in the Excel workbook. Therefore, typical use involves writing a VBA macro that, when triggered, can call back into Python via xlwings’ RunPython function or perform native Excel operations. This creates a hybrid automation model.

Syntax in xlwings:
The call is made through the Excel Application object. The syntax in xlwings is:

app.api.OnTime(EarliestTime, Procedure, LatestTime, Schedule)
  • EarliestTime (Required): The time when the procedure should be run. It is a serial Excel date/time value. In practice, it’s often created using datetime or time modules. Example: datetime.datetime.now() + datetime.timedelta(seconds=10).
  • Procedure (Required): A string specifying the name of the VBA macro to run. This macro must be present in a standard VBA module in the workbook (e.g., “Module1.MyMacro”).
  • LatestTime (Optional): The latest time for the procedure to run. If Excel is not in Ready, Copy, Cut, or Find mode at EarliestTime, it will wait until it enters one of these states, but only until LatestTime. If omitted, Excel waits indefinitely.
  • Schedule (Optional): A boolean value. True to schedule a new OnTime procedure (default). False to clear a previously set procedure that has not yet run.

Code Example:
This example schedules a VBA macro named “RefreshData” to run 5 seconds from now. The VBA macro itself could contain code to call a Python function or refresh queries.

import xlwings as xw
import datetime

# Connect to the active Excel instance or create a new one
app = xw.apps.active

# Calculate the time for execution (5 seconds from now)
run_time = datetime.datetime.now() + datetime.timedelta(seconds=5)

# Schedule the OnTime call. The macro "RefreshData" must exist in the workbook.
app.api.OnTime(EarliestTime=run_time, Procedure="RefreshData")

print(f"Scheduled 'RefreshData' to run at approximately {run_time}")

To cancel a scheduled procedure before it executes, you would call OnTime with the same EarliestTime and Procedure, but set Schedule to False:

# Cancel the previously scheduled "RefreshData" macro
app.api.OnTime(EarliestTime=run_time, Procedure="RefreshData", Schedule=False)

How To Create Gradient Filled Simple 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 = 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 = 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:B9').Select()  #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlColumnClustered,20,20,350,250,True)
cht=shp.Chart  #
cht.ChartGroups(1).GapWidth=50
cht.SeriesCollection(1).Format.Fill.ForeColor.RGB=xw.utils.rgb_to_int((0,0,255))
cht.SeriesCollection(1).Format.Fill.OneColorGradient(1,1,1)    #msoGradientHorizontal
cht.SeriesCollection(1).Format.Line.ForeColor.RGB=xw.utils.rgb_to_int((0,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.OnRepeat in the xlwings API way

The Application.OnRepeat property in Excel VBA is used to assign a macro name (as a string) that will be executed when a user clicks the “Repeat” command. This command is typically available after performing an action that can be repeated, such as via the toolbar or the shortcut Ctrl+Y. In the context of xlwings, which provides a programmatic bridge between Python and Excel’s object model, this property can be accessed and manipulated to automate repetitive tasks within an Excel session. However, it’s important to note that xlwings primarily interacts with Excel through its API, and while it can execute VBA code, directly setting the OnRepeat property is not a standard, out-of-the-box feature because it is deeply tied to the VBA environment and the user interface. Typically, xlwings focuses on data manipulation, analysis, and automation using Python, leaving UI-specific commands like OnRepeat to be handled within VBA if necessary.

Functionally, OnRepeat allows for the customization of what action is repeated, enabling developers to define a specific macro for repetition, which can enhance user efficiency. In xlwings, to work with this property, you would need to use the api property of an xlwings App or Book object to access the underlying Excel Application object from the COM interface. This gives you direct access to VBA properties and methods, including OnRepeat.

The syntax for accessing the OnRepeat property via xlwings is through the Application object’s COM interface. Here’s the general format:

import xlwings as xw

# Connect to the active Excel instance or create a new one
app = xw.apps.active

# Access the OnRepeat property
repeat_macro = app.api.OnRepeat # Get the current value
app.api.OnRepeat = "MacroName" # Set the value to a macro name
  • app: This is an xlwings App object representing the Excel application.
  • api: This property provides access to the pywin32 COM object, which mirrors the Excel Application object from the VBA object model.
  • OnRepeat: This property can be get or set. When getting, it returns a string representing the name of the macro assigned to the Repeat command. When setting, it assigns a macro name (as a string) to the Repeat command. The macro must exist in the workbook’s VBA project.
  • MacroName: A string specifying the name of the macro to be repeated. This macro should be defined in a VBA module within the workbook.

Note: The OnRepeat property is specific to the Excel Application session and may not persist after closing Excel. Also, it requires that macros are enabled in Excel, and the macro must be accessible (e.g., in a standard module).

Here is an example code instance using xlwings to set and use the OnRepeat property:

import xlwings as xw

# Assume Excel is open with a workbook containing a macro named 'RepeatFormatting'
wb = xw.books.active
app = wb.app

# Set the OnRepeat property to 'RepeatFormatting'
app.api.OnRepeat = "RepeatFormatting"

# To demonstrate, we can run the macro once via xlwings (if needed)
# First, ensure the macro is in a module. We can run it using the Run method:
app.api.Run("RepeatFormatting")

# Later, when the user clicks Repeat or presses Ctrl+Y, the 'RepeatFormatting' macro will execute again.

# To retrieve the current OnRepeat setting:
current_repeat = app.api.OnRepeat
print(f"The current Repeat macro is: {current_repeat}")

# To clear the OnRepeat property (set it to an empty string):
app.api.OnRepeat = ""