Archive

How To Create Doughnut 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
    cht.HasTitle = True

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:B11').Select()  #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xlDoughnut,20,20,250,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.AutoFormatAsYouTypeReplaceHyperlinks in the xlwings API way

The AutoFormatAsYouTypeReplaceHyperlinks member of the Application object in Excel is a property that controls whether Excel automatically formats text that resembles a hyperlink address into a clickable hyperlink as you type. This is part of the “AutoFormat as you type” feature, which can help in quickly creating interactive documents by converting typed URLs or network paths into functional links without manual formatting. In xlwings, this property is accessible via the Application object’s API, allowing you to programmatically check or set this automation setting, which can be particularly useful in scripts that prepare or clean Excel workbooks for specific user interactions.

Syntax in xlwings:
In xlwings, you interact with this property through the app object, which represents the Excel Application. The property is exposed as a boolean attribute. The syntax is straightforward:

app.api.AutoFormatAsYouTypeReplaceHyperlinks

This property can be both read and written. When reading, it returns True if the feature is enabled, and False if disabled. When writing, you can set it to True to enable automatic hyperlink formatting, or False to disable it. There are no additional parameters or arguments for this property, as it is a simple toggle.

Example Usage with xlwings:
Below is a practical example demonstrating how to use the AutoFormatAsYouTypeReplaceHyperlinks property in a Python script with xlwings. This example checks the current setting, toggles it based on a condition, and then types some text to observe the effect (if Excel is visible). Note that changes to this setting may affect the user’s Excel session, so it’s often used in controlled environments or reset afterward.

import xlwings as xw

# Start or connect to an Excel application
app = xw.App(visible=True) # Set visible=True to see the typing effect
wb = app.books.add()

# Access the AutoFormatAsYouTypeReplaceHyperlinks property
current_setting = app.api.AutoFormatAsYouTypeReplaceHyperlinks
print(f"Current AutoFormatAsYouTypeReplaceHyperlinks setting: {current_setting}")

# Toggle the setting: enable if disabled, or disable if enabled
new_setting = not current_setting
app.api.AutoFormatAsYouTypeReplaceHyperlinks = new_setting
print(f"Setting changed to: {new_setting}")

# To see the effect, type a URL in a cell (requires Excel to be visible and active)
if app.visible:
    sheet = wb.sheets[0]
    sheet.range('A1').value = "Visit https://www.example.com for more info."
    # If enabled, Excel will format the URL as a hyperlink automatically as you type.
    # Note: In xlwings, setting cell value programmatically may not trigger the "as you type" feature,
    # as it simulates direct value insertion rather than keystroke-by-keystroke typing.
    # The feature primarily works during manual typing in the Excel interface.

    # Restore the original setting (optional, for user convenience)
    app.api.AutoFormatAsYouTypeReplaceHyperlinks = current_setting

# Save and close
wb.save('hyperlink_example.xlsx')
wb.close()
app.quit()

Important Notes:

  • The AutoFormatAsYouTypeReplaceHyperlinks property affects the entire Excel application session, not just a specific workbook. Changing it will influence all open workbooks and future typing actions.
  • In xlwings, when you set a cell’s value using .value, Excel may not apply the “as you type” formatting because it is not simulating real-time keystrokes. The feature is designed for manual entry in the Excel GUI. Therefore, toggling this property via xlwings is more about configuring the environment for user interaction rather than for programmatic data insertion.
  • This property is part of Excel’s application-level options, so it’s persistent across sessions if saved in the user’s settings, but xlwings changes are temporary for the current session unless explicitly saved via Excel’s options dialog.

How to use Application.AutoCorrect in the xlwings API way

The AutoCorrect feature in Excel is a powerful tool for automatically correcting common typing errors, capitalizing days of the year, and expanding text abbreviations. Through xlwings, you can programmatically access and control these settings via the Application object’s AutoCorrect property. This allows for automation of tasks such as disabling auto-capitalization of days, adding custom replacement entries, or checking if a specific text string is in the AutoCorrect list.

Functionality
The AutoCorrect object provides control over Excel’s AutoCorrect options. Key capabilities include:

  • Managing automatic capitalization of days of the week.
  • Controlling the first letter capitalization in sentences.
  • Adding, removing, or checking text replacements (e.g., replacing “(c)” with “©”).
  • Enabling or disabling various auto-formatting features.

Syntax and Parameters
In xlwings, you access it through the app object (an instance of xw.App). The basic syntax is:

app.api.AutoCorrect.MemberName

Where MemberName is a property or method of the AutoCorrect object. Common members include:

MemberTypeDescriptionParameters/Values
CapitalizeNamesOfDaysPropertyGets or sets whether days are auto-capitalized.Boolean (True/False)
TwoInitialCapitalsPropertyControls auto-correction of two initial capitals.Boolean
AddReplacement(What, Replacement)MethodAdds a custom text replacement.What (String): Text to replace. Replacement (String): New text.
DeleteReplacement(What)MethodRemoves a custom replacement.What (String): Text entry to delete.
ReplacementList(Index)PropertyReturns a specific replacement pair.Index (Integer): Position in the list (1-based).

Code Examples
Here are practical examples using xlwings:

  1. Disable auto-capitalization of days:
import xlwings as xw
app = xw.App(visible=False)
app.api.AutoCorrect.CapitalizeNamesOfDays = False
app.quit()
  1. Add a custom text replacement:
import xlwings as xw
app = xw.App(visible=False)
# Replace "xlw" with "xlwings"
app.api.AutoCorrect.AddReplacement("xlw", "xlwings")
app.quit()
  1. Check and delete a replacement:
import xlwings as xw
app = xw.App(visible=False)
# Delete if "xlw" exists in the list
try:
    app.api.AutoCorrect.DeleteReplacement("xlw")
    print("Replacement deleted.")
except Exception as e:
    print("Entry not found:", e)
app.quit()
  1. Iterate through replacement list (first 5 entries):
import xlwings as xw
app = xw.App(visible=False)
ac = app.api.AutoCorrect
for i in range(1, 6):
try:
    item = ac.ReplacementList(i)
    print(f"Index {i}: {item}")
except:
    break
app.quit()

How To Create 3D Pie Chart Using xlwings? 2

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
    cht.HasTitle = True

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:B7').Select()  #
shp=sht.api.Shapes.AddChart2(-1,xw.constants.ChartType.xl3DPie,20,20,250,250,True)
cht=shp.Chart  #
cht.SeriesCollection(1).Points(2).Explosion=16

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.Assistance in the xlwings API way

The Application.Assistance member in Excel’s object model provides access to the Help system, allowing developers to display specific Help topics programmatically. In xlwings, this functionality is exposed through the api property, which grants direct access to the underlying Excel VBA object model. This is particularly useful for creating user-friendly applications where context-sensitive help can be triggered based on user actions or inputs.

Functionality:
The primary purpose of Application.Assistance is to show a designated Help topic to the user. It can display built-in Excel Help topics using their unique Help IDs, which are often numeric or string identifiers. This enables developers to guide users directly to relevant documentation without requiring them to manually search through the Help system.

Syntax:
In xlwings, the syntax to call this member is:

app.api.Assistance.ShowHelp(HelpFile, HelpContextID)
  • HelpFile: This is a string parameter that specifies the name of the Help file. For built-in Excel Help, this is typically set to "" (an empty string) or None to use the default Excel Help file. If using a custom Help file, provide its full path or name.
  • HelpContextID: This parameter can be a string or numeric value that identifies the specific Help topic. For Excel’s built-in topics, this ID is often a numeric code corresponding to a particular subject. The exact IDs can be found in Excel’s VBA object model documentation or through developer resources. For example, the Help ID for the “Format Cells” dialog is "xlMainWindow" or a specific numeric ID like 27010 for certain topics.

Example:
Below is an xlwings code example that demonstrates how to use Application.Assistance to display a Help topic. This example assumes Excel is already running and a workbook is open via xlwings.

import xlwings as xw

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

# Display a built-in Excel Help topic, e.g., for general assistance
# Using an empty string for HelpFile defaults to Excel's Help
# The HelpContextID "xlMainWindow" opens the main Help window
app.api.Assistance.ShowHelp(HelpFile="", HelpContextID="xlMainWindow")

# Alternatively, to show a specific topic by numeric ID (example ID)
# This might open a topic like "About Excel" (ID varies by version)
app.api.Assistance.ShowHelp(HelpFile="", HelpContextID=27010)

# For a custom Help file (if available), specify the file path
# app.api.Assistance.ShowHelp(HelpFile="C:\\Help\\CustomHelp.chm", HelpContextID=100)

Notes:

  • The effectiveness of this method depends on the availability and correctness of Help IDs. Some IDs may change between Excel versions, so testing across versions is recommended.
  • If the HelpFile parameter is left empty and a valid HelpContextID is provided, Excel will attempt to open the corresponding topic in its default Help system.
  • In cases where the Help topic cannot be found, Excel may display a generic Help window or an error, depending on the version.