Blog
How to use Application.DisplayDocumentInformationPanel in the xlwings API way
The Application.DisplayDocumentInformationPanel property in Excel’s object model controls the visibility of the Document Information Panel (DIP) for the active workbook. This panel, when visible, typically displays metadata properties of the document based on its associated content type or custom XML parts. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel VBA object model. Using this property, you can programmatically check whether the panel is currently displayed or change its visibility state, which can be useful in automation scripts that manage the user interface or document properties workflow.
Functionality
The primary function is to get or set a Boolean value indicating if the Document Information Panel is visible. This can help in UI automation, ensuring a consistent interface state, or in processes where metadata entry or review is required.
Syntax in xlwings
# To get the current visibility state
visible = xw.apps[0].api.DisplayDocumentInformationPanel
# To set the visibility state (True to show, False to hide)
xw.apps[0].api.DisplayDocumentInformationPanel = True
- Property Type: Read/write Boolean.
- Return Value: When getting, it returns
Trueif the panel is visible; otherwise,False. - Parameter for Setting: A Boolean value (
TrueorFalse). Setting it toTruedisplays the panel;Falsehides it. Note that the effect might depend on the workbook’s properties and Excel’s configuration.
Code Examples
Here are practical xlwings API examples demonstrating its usage:
- Check and Report Current Visibility
import xlwings as xw
# Connect to the active Excel instance
app = xw.apps.active
# Get the current state of the Document Information Panel
is_visible = app.api.DisplayDocumentInformationPanel
# Output the result
if is_visible:
print("The Document Information Panel is currently visible.")
else:
print("The Document Information Panel is currently hidden.")
- Toggle the Panel Visibility
import xlwings as xw
app = xw.apps.active
# Toggle the visibility: if visible, hide it; if hidden, show it
current_state = app.api.DisplayDocumentInformationPanel
app.api.DisplayDocumentInformationPanel = not current_state
print(f"Toggled the panel. New state: {app.api.DisplayDocumentInformationPanel}")
- Ensure the Panel is Hidden for a Clean UI
import xlwings as xw
# Start or connect to Excel
app = xw.App(visible=True) # Make Excel visible
app.books.add() # Open a new workbook
# Force the Document Information Panel to be hidden
app.api.DisplayDocumentInformationPanel = False
print("Document Information Panel has been hidden.")
How To Create Kernel Density Estimation Curve with Color Fill Using xlwings?
【Example】

【Code】
import xlwings as xw
import numpy as np
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 = 'Values'
ax1.AxisTitle.Font.Size = 10
ax1.TickLabels.Font.Size = 8
ax1.TickLabels.NumberFormat = '0.00'
ax1.HasMajorGridlines = True
ax2.HasTitle = True
ax2.AxisTitle.Text = 'Probability'
ax2.AxisTitle.Font.Size = 10
ax2.TickLabels.Font.Size = 8
ax2.HasMajorGridlines = True
cht.HasTitle = True
cht.ChartTitle.Caption = 'KDE Plot'
cht.ChartTitle.Font.Size = 12
def kde(data,x,h):
#一元核密度估计
my_sum=0
count=0
for i in data:
my_sum+=(1/np.sqrt(2*3.1415926))*\
np.exp(-0.5*((x-i)/h)*((x-i)/h))
count+=1
return my_sum/count/h
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')
data=sht.range('A2:A61').value
app.kill()
#从comtypes包中导入CreateObject函数
from comtypes.client import CreateObject
app2=CreateObject("Excel.Application") #创建Excel应用
app2.Visible=True #应用窗口可见
app2.ScreenUpdating=False
wb2=app2.Workbooks.Open(root+r'/data.xlsx') #添加工作簿
sht2=wb2.Sheets('Sheet1') #获取第1个工作表
shp=sht2.Shapes.AddChart2()
shp.Left=20
cht=shp.Chart #添加图表
cht.ChartType=-4169
ax1=cht.Axes(1)
ax2=cht.Axes(2)
ax1.MinimumScale=-5.9
ax1.MaximumScale=12
ax2.MinimumScale=0
ax2.MaximumScale=0.15
ax1.CrossesAt=ax1.MinimumScale
ax2.CrossesAt=ax2.MinimumScale
set_style(cht)
kdex=[0 for _ in range(180)]
kdef=[0 for _ in range(180)]
for i in range(180):
kdex[i]=(i-59)/10
kdef[i]=kde(data,(i-59)/10,1.5)
cht.SeriesCollection().NewSeries()
#画填充多边形
pt=[[0 for _ in range(2)] for _ in range(183)]
for i in range(180):
pt[i][0]=shape_x(cht,kdex[179-i])
pt[i][1]=shape_y(cht,kdef[179-i])
pt[180][0]=pt[179][0]
pt[180][1]=shape_y(cht,0)
pt[181][0]=pt[0][0]
pt[181][1]=shape_y(cht,0)
pt[182][0]=pt[0][0]
pt[182][1]=pt[0][1]
shp2=cht.Shapes.AddPolyline(pt)
shp2.Fill.ForeColor.RGB=xw.utils.rgb_to_int((0,0,255))
shp2.Fill.Transparency = 0.5
shp2.Line.ForeColor.RGB=xw.utils.rgb_to_int((0,0,255))
shp2.Line.Weight=2
app2.ScreenUpdating=True
cht.Export(root+'/cht.jpg')
cht.Export(root+'/cht.svg')
cht.ExportAsFixedFormat(0,root+'/cht.pdf')
#wb2.Save()
#os.system('taskkill /f /im EXCEL.EXE')

How to use Application.DisplayDocumentActionTaskPane in the xlwings API way
The DisplayDocumentActionTaskPane property of the Application object in Excel’s object model controls the visibility of the Document Actions task pane, which is used for working with smart documents and XML expansions. In xlwings, this functionality is exposed through the api property, allowing direct access to the underlying Excel VBA object model. This property is particularly useful when automating workbooks that utilize smart document solutions or XML mappings, enabling developers to programmatically show or hide the associated task pane to streamline the user interface during automated processes.
Functionality:
The DisplayDocumentActionTaskPane property is a read/write Boolean property that determines whether the Document Actions task pane is displayed in the Excel application window. When set to True, the task pane is visible; when False, it is hidden. This can enhance user experience by automatically managing task pane visibility based on the context of the automation script, such as hiding it during data processing to reduce clutter or showing it when user interaction with smart document features is required.
Syntax in xlwings:
In xlwings, you access this property via the Application object obtained from a workbook or app instance. The typical syntax is:
app = xw.App() # Get the Excel application instance
app.api.DisplayDocumentActionTaskPane = True # Set to True to display, False to hide
current_state = app.api.DisplayDocumentActionTaskPane # Read the current state
Here, app.api provides the raw Excel VBA object model interface. The DisplayDocumentActionTaskPane property does not take any parameters; it simply gets or sets a Boolean value. Note that this property may not be available in all Excel versions or configurations, particularly if smart document features are not enabled. It is recommended to check the Excel environment or handle potential errors when using it.
Code Examples:
Below are practical examples demonstrating how to use DisplayDocumentActionTaskPane with xlwings in Python.
- Displaying the Document Actions Task Pane:
This example shows how to make the task pane visible when opening a workbook that uses smart document functionality.
import xlwings as xw
# Start Excel and open a workbook
app = xw.App(visible=True)
workbook = app.books.open('SmartDocument.xlsx')
# Display the Document Actions task pane
app.api.DisplayDocumentActionTaskPane = True
print("Document Actions task pane is now visible.")
# Keep the application open for demonstration
input("Press Enter to hide the task pane and close...")
# Hide the task pane before closing
app.api.DisplayDocumentActionTaskPane = False
app.quit()
- Toggling Task Pane Visibility Based on Content:
In this example, the script checks for XML mappings in a workbook and toggles the task pane accordingly.
import xlwings as xw
app = xw.App(visible=True)
wb = app.books.open('DataWithXML.xlsx')
# Check if the workbook has XML maps (simplified condition)
has_xml_maps = len(wb.api.XmlMaps) > 0
if has_xml_maps:
app.api.DisplayDocumentActionTaskPane = True
print("XML maps detected. Document Actions task pane displayed.")
else:
app.api.DisplayDocumentActionTaskPane = False
print("No XML maps found. Task pane hidden.")
# Perform some data operations
sheet = wb.sheets[0]
sheet.range('A1').value = 'Updated Data'
# Hide task pane after operations
app.api.DisplayDocumentActionTaskPane = False
wb.save()
app.quit()
- Reading the Current State:
This example retrieves the current visibility status of the task pane for logging or conditional logic.
import xlwings as xw
app = xw.App(visible=True)
wb = app.books.add()
# Read the current display state
is_displayed = app.api.DisplayDocumentActionTaskPane
print(f"Document Actions task pane visible: {is_displayed}")
# Toggle based on current state
if not is_displayed:
app.api.DisplayDocumentActionTaskPane = True
print("Task pane has been turned on.")
app.quit()
How To Create Univariate Kernel Density Estimation Curve Using xlwings?
【Example】

【Code】
import xlwings as xw
import numpy as np
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 = 'Values'
ax1.AxisTitle.Font.Size = 10
ax1.TickLabels.Font.Size = 8
ax1.TickLabels.NumberFormat = '0.00'
ax1.HasMajorGridlines = True
ax2.HasTitle = True
ax2.AxisTitle.Text = 'Probability'
ax2.AxisTitle.Font.Size = 10
ax2.TickLabels.Font.Size = 8
ax2.HasMajorGridlines = True
cht.HasTitle = True
cht.ChartTitle.Caption = 'KDE Plot'
cht.ChartTitle.Font.Size = 12
def kde(data,x,h):
#一元核密度估计
my_sum=0
count=0
for i in data:
my_sum+=(1/np.sqrt(2*3.1415926))*\
np.exp(-0.5*((x-i)/h)*((x-i)/h))
count+=1
return my_sum/count/h
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')
data=sht.range('A2:A61').value
app.kill()
#从comtypes包中导入CreateObject函数
from comtypes.client import CreateObject
app2=CreateObject("Excel.Application") #创建Excel应用
app2.Visible=True #应用窗口可见
app2.ScreenUpdating=False
wb2=app2.Workbooks.Open(root+r'/data.xlsx') #添加工作簿
sht2=wb2.Sheets('Sheet1') #获取第1个工作表
shp=sht2.Shapes.AddChart2()
shp.Left=20
cht=shp.Chart #添加图表
cht.ChartType=-4169
ax1=cht.Axes(1)
ax2=cht.Axes(2)
ax1.MinimumScale=-5.9
ax1.MaximumScale=12
ax2.MinimumScale=0
ax2.MaximumScale=0.15
ax1.CrossesAt=ax1.MinimumScale
ax2.CrossesAt=ax2.MinimumScale
set_style(cht)
kdex=[0 for _ in range(180)]
kdef=[0 for _ in range(180)]
for i in range(180):
kdex[i]=(i-59)/10
kdef[i]=kde(data,(i-59)/10,1.5)
cht.SeriesCollection().NewSeries()
#画填充多边形
pt=[[0 for _ in range(2)] for _ in range(183)]
for i in range(180):
pt[i][0]=shape_x(cht,kdex[179-i])
pt[i][1]=shape_y(cht,kdef[179-i])
pt[180][0]=pt[179][0]
pt[180][1]=shape_y(cht,0)
pt[181][0]=pt[0][0]
pt[181][1]=shape_y(cht,0)
pt[182][0]=pt[0][0]
pt[182][1]=pt[0][1]
shp2=cht.Shapes.AddPolyline(pt)
shp2.Fill.Visible=False
shp2.Line.ForeColor.RGB=xw.utils.rgb_to_int((0,0,255))
shp2.Line.Weight=1.5
app2.ScreenUpdating=True
cht.Export(root+'/cht.jpg')
cht.Export(root+'/cht.svg')
cht.ExportAsFixedFormat(0,root+'/cht.pdf')
#wb2.Save()
#os.system('taskkill /f /im EXCEL.EXE')

How to use Application.DisplayCommentIndicator in the xlwings API way
The DisplayCommentIndicator property in the Excel Application object determines how cell comments (also known as notes) are visually indicated within a worksheet. This setting is crucial for controlling the visibility of comment indicators, which are the small red triangles typically found in the top-right corner of cells containing comments. By adjusting this property, users can tailor the display to suit different workflows, such as hiding indicators for a cleaner view or showing them only when comments are present. This property is particularly useful in collaborative environments where comment tracking is essential, or when preparing reports where visual clutter should be minimized.
In xlwings, the DisplayCommentIndicator property can be accessed through the Application object. The syntax for using this property is straightforward: app.display_comment_indicator. Here, app refers to an instance of the xlwings App class, which represents the Excel application. The property accepts integer values that correspond to specific display modes, as defined in Excel’s object model. The possible values and their meanings are as follows:
-1: Displays comment indicators only when comments are present (default). This is the standard setting where red triangles appear in cells with comments.0: Hides comment indicators entirely. In this mode, no visual cues are shown, even if cells contain comments, which can make the worksheet look cleaner but may hide important annotations.1: Always shows comment indicators, regardless of whether comments are present. This mode is less common but can be used for consistency in certain templates or to highlight cells intended for comments.
To set or retrieve the DisplayCommentIndicator property in xlwings, you first need to establish a connection to the Excel application. For example, you can use xlwings.App() to launch a new instance or connect to an existing one. Once the application object is available, you can directly assign or read the property value. This property is application-wide, meaning it affects all open workbooks and worksheets in that Excel instance. It is important to note that changes made via xlwings are immediately reflected in the Excel interface, allowing for dynamic adjustments during automation scripts.
Here are some practical xlwings API code examples demonstrating the use of the DisplayCommentIndicator property:
- Retrieving the current display setting:
import xlwings as xw
app = xw.App(visible=True) # Start or connect to Excel
current_setting = app.display_comment_indicator
print(f"Current DisplayCommentIndicator setting: {current_setting}")
# This will output -1, 0, or 1 based on the current configuration.
app.quit() # Close the application
- Hiding comment indicators for a cleaner view:
import xlwings as xw
app = xw.App(visible=True)
app.display_comment_indicator = 0 # Hide indicators
print("Comment indicators are now hidden.")
# You can open a workbook here to see the effect, e.g., app.books.open('example.xlsx')
app.quit()
- Showing indicators only when comments exist (default reset):
import xlwings as xw
app = xw.App(visible=False) # Run in background
app.display_comment_indicator = -1 # Set to default
print("DisplayCommentIndicator reset to default (show only with comments).")
app.quit()
- Always displaying comment indicators for consistency:
import xlwings as xw
with xw.App(visible=True) as app: # Using context manager for automatic cleanup
app.display_comment_indicator = 1 # Always show indicators
wb = app.books.open('sample.xlsx')
# The workbook will now show red triangles in all cells, even empty ones.
wb.save()
# The setting persists until changed or Excel is restarted.
How To Create Bivariate Histogram 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))
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')
x=sht.range('A1:A1000').value
y=sht.range('B1:B1000').value
#频数分析
bx=10
by=10
minx=9999
maxx=-9999
miny=9999
maxy=-9999
for i in range(1000):
if minx>x[i]: minx=x[i]
if maxx<x[i]: maxx=x[i]
if miny>y[i]: miny=y[i]
if maxy<y[i]: maxy=y[i]
difx=maxx-minx
dify=maxy-miny
stepx=difx/bx
stepy=dify/by
count=[[0 for _ in range(10)] for _ in range(10)]
xi=[0 for _ in range(11)]
xi2=[0 for _ in range(11)]
xi[0]=minx
xi2[0]=minx+stepx/2
for i in range(1,11):
xi[i]=xi[i-1]+stepx
if i!=10:
xi2[i]=xi[i]+stepx/2
yi=[0 for _ in range(11)]
yi2=[0 for _ in range(11)]
yi[0]=miny
yi2[0]=miny+stepy/2
for i in range(1,11):
yi[i]=yi[i-1]+stepy
if i!=10:
yi2[i]=yi[i]+stepy/2
for k in range(1000):
for i in range(10):
if x[k]>=xi[i] and x[k]<xi[i+1]:
for j in range(10):
if y[k]>=yi[j] and y[k]<yi[j+1]:
count[i][j]+=1
#输出频数到sheet2
sht2=wb.sheets.add()
for i in range(1,11):
for j in range(1,11):
sht2.api.Cells(i+1,j+1).Value=count[i-1][j-1]
#根据频数绘制二元直方图
shp=sht2.api.Shapes.AddChart2(286,xw.constants.ChartType.xl3DColumn)
shp.Left=20
cht=shp.Chart
if cht.SeriesCollection().Count>0:
for i in range(cht.SeriesCollection().Count,0,-1):
cht.SeriesCollection(i).Delete()
cht.Legend.Delete()
countj=[0 for _ in range(10)]
for i in range(10):
countj[i]=count[i][:]
cht.SeriesCollection().NewSeries()
cht.SeriesCollection(i+1).Name=str(yi2[i]) #序列轴刻度标签
cht.SeriesCollection(i+1).XValues=xi2 #分类轴刻度标签
cht.SeriesCollection(i+1).Values=countj[i] #Z轴
cht.ChartGroups(1).GapWidth=0
cht.GapDepth=0
for i in range(10):
fl=cht.SeriesCollection(i+1).Format.Fill
fl.ForeColor.ObjectThemeColor=5 #msoThemeColorAccent1
#fl.ForeColor.TintAndShade = 0
fl.ForeColor.Brightness=0
fl.Solid()
ln=cht.SeriesCollection(i+1).Format.Line
ln.Visible=True
ln.ForeColor.ObjectThemeColor=13 #msoThemeColorText1
#ln.ForeColor.TintAndShade = 0
ln.ForeColor.Brightness=0.0500000007
cht.Export(root+'/cht.jpg')
cht.Export(root+'/cht.svg')
cht.ExportAsFixedFormat(0,root+'/cht.pdf')
#wb.save()
#app.kill()

How to use Application.DisplayClipboardWindow in the xlwings API way
The DisplayClipboardWindow member of the Application object in Excel is a property that controls the visibility of the Clipboard task pane. This pane appears when you copy or cut multiple items in Excel, allowing you to view and manage the clipboard history. In automation scripts using xlwings, this property is useful for managing the user interface state, particularly when you want to ensure a clean interface during macro execution or toggling the pane for specific tasks.
In xlwings, the Application object is accessed via the app property of a Book object or by creating an application instance directly. The DisplayClipboardWindow property is a read/write Boolean property, meaning you can both retrieve its current state and set it to a new value. The syntax for accessing this property in xlwings is straightforward, as it directly mirrors the VBA object model but uses Python’s attribute style.
Syntax and Parameters:
- Property Access:
app.api.DisplayClipboardWindow - This returns or sets a Boolean value (
TrueorFalse). apprefers to the xlwings application instance (e.g.,xw.apps.activeor a newly created one).- The
.apiattribute is used to access the underlying Excel object model, ensuring compatibility with Excel’s native properties and methods. - Value Explanation:
True: Makes the Clipboard task pane visible.False: Hides the Clipboard task pane.- Note: There are no additional parameters for this property. It is a simple toggle that affects the Excel application’s UI.
Example Usage:
Below are practical xlwings code examples demonstrating how to use the DisplayClipboardWindow property in various scenarios.
- Checking the Current State:
You can retrieve whether the Clipboard pane is currently displayed to inform your script’s logic.
import xlwings as xw
# Connect to the active Excel instance
app = xw.apps.active
# Get the current display state
is_visible = app.api.DisplayClipboardWindow
print(f"Clipboard window is visible: {is_visible}")
- Hiding the Clipboard Pane:
To ensure a distraction-free interface during automation, you might hide the pane.
import xlwings as xw
# Start a new Excel instance (or use an existing one)
app = xw.App(visible=True) # Set visible=True to see Excel UI
# Hide the Clipboard task pane
app.api.DisplayClipboardWindow = False
# Perform other tasks, like data manipulation
book = app.books.add()
book.sheets[0].range("A1").value = "Sample data"
# Keep the pane hidden until end
app.quit() # Close the application
- Toggling Visibility Based on Condition:
You can conditionally show or hide the pane, such as when copying multiple items.
import xlwings as xw
app = xw.apps.active
# Assume we want to show the pane only if performing a multi-copy operation
multi_copy_needed = True # This could be determined by your script's logic
if multi_copy_needed:
app.api.DisplayClipboardWindow = True
print("Clipboard pane shown for multi-copy tasks.")
else:
app.api.DisplayClipboardWindow = False
print("Clipboard pane hidden.")
- Integrating with Other Operations:
Combine with copying data to leverage the clipboard functionality.
import xlwings as xw
app = xw.apps.active
book = app.books.active
# Show the Clipboard pane before copying
app.api.DisplayClipboardWindow = True
# Copy a range of data
book.sheets[0].range("A1:B10").copy()
# The pane will now display the copied items; you can then hide it after a delay or task
import time
time.sleep(2) # Wait 2 seconds to let user see the pane
app.api.DisplayClipboardWindow = False
How To Create Univariate Histogram 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
def draw_hist(sht,n):
#频数分析
x=sht.range('A1:A1000').value
xi=[0 for _ in range(11)]
xi2=[0 for _ in range(10)]
count=[0 for _ in range(10)]
bx=10
minx=9999
maxx=-9999
for i in range(n):
if minx>x[i]:
minx=x[i]
if maxx<x[i]:
maxx=x[i]
difx=maxx-minx
stepx=difx/bx
for i in range(10):
count[i]=0
xi[0]=minx
xi2[0]=minx+stepx/2
for i in range(1,11):
xi[i]=xi[i-1]+stepx
if i!=10:
xi2[i]=xi[i]+stepx/2
for i in range(n):
for j in range(10):
if x[i]>=xi[j] and x[i]<xi[j+1]:
count[j]+=1
#根据频数绘制直方图
sht.api.Range('D3').Select()
shp=sht.api.Shapes.AddChart2()
shp.Left=20
cht=shp.Chart
for i in range(cht.SeriesCollection().Count,0,-1):
cht.SeriesCollection(i).Delete()
cht.SeriesCollection().NewSeries()
cht.SeriesCollection(1).ChartType=xw.constants.ChartType.xlColumnClustered
cht.SeriesCollection(1).XValues=xi2
cht.SeriesCollection(1).Values=count
cht.ChartGroups(1).GapWidth=0
cht.GapDepth=0
fl=cht.SeriesCollection(1).Format.Fill
fl.ForeColor.ObjectThemeColor=5 #msoThemeColorAccent1
#fl.ForeColor.TintAndShade=0
fl.ForeColor.Brightness=0
fl.Solid()
ln=cht.SeriesCollection(1).Format.Line
ln.Visible=True
ln.ForeColor.ObjectThemeColor=13 #msoThemeColorText1
#ln.ForeColor.TintAndShade=0
ln.ForeColor.Brightness=0.0500000007
return cht
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')
cht=draw_hist(sht,1000)
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.DisplayAlerts in the xlwings API way
The DisplayAlerts property of the Application object in Excel is a crucial setting for controlling how Excel handles user prompts and alert messages during automated operations. When automating tasks with xlwings, managing these alerts can significantly streamline your code by preventing interruptions that require manual responses. By setting DisplayAlerts to False, you can suppress common dialog boxes—such as those asking for confirmation to save changes, overwrite files, or delete sheets—allowing your script to run uninterrupted. This is particularly useful in batch processing or when integrating Excel automation into larger workflows where user interaction is not desired. However, it’s important to use this property judiciously; turning off alerts means Excel will take default actions without warning, which could lead to unintended data loss if not handled carefully. Always ensure your code includes proper error handling and saving logic when DisplayAlerts is disabled.
In xlwings, you can access the DisplayAlerts property through the App object, which represents the Excel application. The syntax for setting or getting this property is straightforward. To set it, you assign a boolean value; to retrieve the current state, you simply read the property. The property accepts True or False values, where True enables alerts (the default Excel behavior) and False disables them. There are no additional parameters required. For reference:
- Property Type: Read/write boolean.
- Default Value:
True(alerts are displayed). - Usage: Control the display of alert messages and prompts.
Here is the basic xlwings API call format:
import xlwings as xw
# Connect to an existing Excel instance or start a new one
app = xw.apps.active # Or use xw.App() for a new instance
# Disable alerts
app.display_alerts = False
# Enable alerts
app.display_alerts = True
# Check the current status
current_status = app.display_alerts
print(f"DisplayAlerts is set to: {current_status}")
Below are practical examples demonstrating the use of DisplayAlerts in xlwings:
Example 1: Suppressing Save Prompts
When closing a workbook without saving, Excel typically prompts the user to save changes. By disabling alerts, you can avoid this prompt and close the workbook directly. This example opens a workbook, makes a change, and closes it without saving, using DisplayAlerts to bypass the confirmation dialog.
import xlwings as xw
# Start Excel and open a workbook
app = xw.App(visible=False) # Run in background
wb = app.books.open('example.xlsx')
# Disable alerts to suppress save prompts
app.display_alerts = False
# Modify the workbook (e.g., write a value)
wb.sheets[0].range('A1').value = 'Test'
# Close without saving; no prompt will appear
wb.close()
# Re-enable alerts if needed for subsequent operations
app.display_alerts = True
app.quit()
Example 2: Overwriting Files Without Confirmation
When saving a workbook with SaveAs to an existing file, Excel usually asks for confirmation to overwrite. Setting DisplayAlerts to False allows the overwrite to occur silently. This example saves a workbook to a path that may already have a file, ensuring no interruption.
import xlwings as xw
# Connect to an active Excel instance
app = xw.apps.active
wb = app.books.active
# Turn off alerts to avoid overwrite confirmation
app.display_alerts = False
# Save to a location; if file exists, it will be overwritten automatically
wb.save(r'C:\path\to\existing_file.xlsx')
# Restore alert display
app.display_alerts = True
Example 3: Deleting Sheets Without Warning
Excel prompts for confirmation when deleting a worksheet. With DisplayAlerts disabled, the sheet deletion proceeds without user intervention. This example removes a specific sheet from a workbook seamlessly.
import xlwings as xw
# Access the current Excel application
app = xw.apps.active
wb = app.books.active
# Disable alerts to suppress delete confirmation
app.display_alerts = False
# Delete a sheet by name; no dialog will pop up
if 'SheetToDelete' in [sheet.name for sheet in wb.sheets]:
wb.sheets['SheetToDelete'].delete()
# Re-enable alerts after the operation
app.display_alerts = True
How To Create Lollipop Plot Using xlwings?
【Example】

【Code】
import xlwings as xw
import numpy as np
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 = 'Values'
ax1.AxisTitle.Font.Size = 10
ax1.TickLabels.Font.Size = 8
#ax1.TickLabels.NumberFormat = '0.00'
ax1.HasMajorGridlines = True
ax1.HasMinorGridlines = True
ax2.HasTitle = True
ax2.AxisTitle.Text = 'Categories'
ax2.AxisTitle.Font.Size = 10
ax2.TickLabels.Font.Size = 8
ax2.HasMajorGridlines = True
ax2.HasMinorGridlines = True
cht.HasTitle = True
#cht.ChartTitle.Caption = 'Plot'
#cht.ChartTitle.Font.Size = 12
def draw_rnd_scatter(cht,x,y,n,r,g,b):
'''绘制散点图
x: X坐标 y(0 to n-1): Y坐标
'''
ser=cht.SeriesCollection().NewSeries()
ser.ChartType=xw.constants.ChartType.xlXYScatter
ser.XValues=x
ser.Values=y
ser.Format.Line.ForeColor.RGB=xw.utils.rgb_to_int((0,0,0))
ser.Format.Fill.ForeColor.RGB=xw.utils.rgb_to_int((r,g,b))
ser.MarkerSize=22
for i in range(n):
lf=shape_x(cht,x[i]-0.04)
tp=shape_y(cht,y[i]+0.3)
wd=cht.PlotArea.InsideWidth/(cht.Axes(1).MaximumScale-cht.Axes(1).MinimumScale)*0.08
ht=cht.PlotArea.InsideHeight/(cht.Axes(2).MaximumScale-cht.Axes(2).MinimumScale)*0.6
shp=cht.Shapes.AddLabel(1,lf,tp,wd,ht)
shp.TextFrame2.TextRange.Characters.Text=str(x[i])
shp.TextFrame2.TextRange.Characters.Font.Size=8
shp.TextFrame.HorizontalAlignment=xw.constants.HAlign.xlHAlignCenter
shp.TextFrame.VerticalAlignment=xw.constants.VAlign.xlVAlignCenter
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')
shp=sht.api.Shapes.AddChart2()
shp.Left=20
shp.Top=20
shp.Width=220
shp.Height=320
cht=shp.Chart #添加图表
cht.ChartType=xw.constants.ChartType.xlXYScatter
ax1=cht.Axes(1)
ax2=cht.Axes(2)
ax1.MinimumScale=0
ax1.MaximumScale=0.28
ax2.MinimumScale=0
ax2.MaximumScale=11
set_style(cht)
data=sht.range('B2:C11').value
dt=np.transpose(data)
dt1=dt[0]
dt2=dt[1]
#绘线形图
for i in range(10):
ser=cht.SeriesCollection().NewSeries()
ser.ChartType=xw.constants.ChartType.xlXYScatterLinesNoMarkers
ser.XValues=[0,dt1[i]]
ser.Values=[dt2[i],dt2[i]]
ser.Format.Line.ForeColor.RGB=xw.utils.rgb_to_int((0,0,255))
ser.Format.Line.Weight=1
#绘散点图
draw_rnd_scatter(cht,dt1,dt2,10,255,128,0)
cht.HasLegend=False
cht.Export(root+'/cht.jpg')
cht.Export(root+'/cht.svg')
cht.ExportAsFixedFormat(0,root+'/cht.pdf')
#wb.save()
#app.kill()
