Archive

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()

How to use Application.Dialogs in the xlwings API way

The Dialogs member of the Application object in xlwings provides programmatic access to many of Excel’s built-in dialog boxes. This feature allows developers to display standard Excel dialogs, retrieve user input from them, and execute the corresponding actions without manually interacting with the Excel interface. It is particularly useful for automating tasks that require user interaction in a familiar Excel dialog format, such as opening files, saving workbooks, or printing settings.

Functionality:
The Dialogs collection represents the various dialog boxes available in Excel. By using the Dialogs property, you can show a specific dialog, wait for user input, and then proceed based on the user’s actions. This can streamline workflows in automated scripts where some steps require manual input or confirmation via Excel’s native UI elements.

Syntax:
In xlwings, you access the Dialogs member through the Application object. The general syntax to show a dialog is:

app.api.Dialogs[Index].Show()

Here, app is an xlwings App instance representing the Excel application. The api property provides access to the underlying Excel object model. Index is a constant or value that specifies which dialog to display. The Show() method displays the dialog and returns a Boolean value: True if the user clicks OK (or equivalent), and False if the user cancels or closes the dialog.

The Index parameter corresponds to Excel’s built-in dialog constants. In xlwings, you can use integer values or constants from the win32com.client.constants module if on Windows. For example, common dialog indices include:

  • 1: Open dialog (xlDialogOpen)
  • 2: Save As dialog (xlDialogSaveAs)
  • 8: Print dialog (xlDialogPrint)
  • 9: Printer setup dialog (xlDialogPrinterSetup)
  • 54: Font dialog (xlDialogFont)

To find the index for a specific dialog, refer to Excel’s VBA object model documentation or use online resources listing Excel dialog constants.

Example Usage:
Below is an xlwings code example that demonstrates using the Dialogs member to display the Open and Print dialogs, handling user responses:

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()

try:
    # Show the Open dialog (Index = 1)
    result_open = app.api.Dialogs[1].Show()
    if result_open:
        print("User selected a file to open via the Open dialog.")
    else:
        print("User canceled the Open dialog.")

    # Show the Print dialog (Index = 8)
    result_print = app.api.Dialogs[8].Show()
    if result_print:
        print("User confirmed printing via the Print dialog.")
    else:
        print("User canceled the Print dialog.")

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

finally:
    # Ensure proper cleanup if needed
    if not xw.apps.active:
        app.quit()

How To Create Stem Chart 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,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=6    


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.3
ax2.MinimumScale=0
ax2.MaximumScale=16

set_style(cht)

data=sht.range('B2:C16').value
dt=np.transpose(data)
dt1=dt[0]
dt2=dt[1]

#绘线形图
for i in range(15):
    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,0,0,255)

cht.HasLegend=False

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

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

How to use Application.DeferAsyncQueries in the xlwings API way

The DeferAsyncQueries property of the Application object in Excel is a Boolean value that controls whether asynchronous queries (such as those from Power Query or external data connections) are deferred during the workbook’s opening process. When set to True, Excel postpones the execution of these queries until after the workbook has fully opened, which can significantly improve the initial load time, especially for workbooks with complex data connections. When set to False (the default), asynchronous queries run as usual during the opening sequence. This property is particularly useful for automating the opening of large workbooks in xlwings scripts, allowing you to manage performance and data refresh timing programmatically.

Syntax in xlwings:
The property is accessed through the xlwings App object, which represents the Excel Application. The syntax is straightforward:

app.api.DeferAsyncQueries

This property is both readable and writable. You can assign a Boolean value (True or False) to it to change its state.

  • Get the current value: current_state = app.api.DeferAsyncQueries
  • Set the value: app.api.DeferAsyncQueries = True

There are no parameters for this property itself. Its behavior is simply toggled by the Boolean assignment.

Code Example:
The following xlwings code demonstrates a practical use case. It opens a workbook with heavy external data connections, defers the queries to speed up the opening process, performs some other operations, and then manually triggers a refresh of all connections.

import xlwings as xw

# Start Excel application (visible for demonstration)
app = xw.App(visible=True)

# Enable deferral of asynchronous queries before opening the workbook
app.api.DeferAsyncQueries = True

# Open the target workbook
wb = app.books.open(r'C:\Path\To\Your\Large_Workbook.xlsx')

# At this point, the workbook is open, but queries are not yet run.
# Perform other operations, such as reading static data or writing formulas.
sheet = wb.sheets['Report']
summary_value = sheet.range('A1').value
print(f"Initial summary value: {summary_value}")

# Now, disable deferral and refresh all external data connections.
app.api.DeferAsyncQueries = False
wb.api.RefreshAll()

# Wait a moment for refresh to complete, then get updated data.
import time
time.sleep(5) # Simple pause; in production, consider checking query status.
updated_value = sheet.range('A1').value
print(f"Refreshed summary value: {updated_value}")

# Save and close
wb.save()
wb.close()
app.quit()

How To Create Dumbbell 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,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((r,g,b))
    ser.Format.Fill.ForeColor.RGB=xw.utils.rgb_to_int((r,g,b))
    ser.MarkerSize=6    


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=250
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.25
ax2.MinimumScale=0
ax2.MaximumScale=11

set_style(cht)

data=sht.range('B2:D11').value
dt=np.transpose(data)
dt1=dt[0]
dt2=dt[1]
dt3=dt[2]

#绘线形图
for i in range(10):
    ser=cht.SeriesCollection().NewSeries()
    ser.ChartType=xw.constants.ChartType.xlXYScatterLinesNoMarkers
    ser.XValues=[dt1[i],dt2[i]]
    ser.Values=[dt3[i],dt3[i]]
    ser.Format.Line.ForeColor.RGB=xw.utils.rgb_to_int((0,0,255))
    ser.Format.Line.Weight=1.5
  
#绘散点图
draw_rnd_scatter(cht,dt1,dt3,0,0,255)
draw_rnd_scatter(cht,dt2,dt3,255,128,0)

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

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

How to use Application.DefaultWebOptions in the xlwings API way

The Application.DefaultWebOptions property in Excel’s object model provides access to a DefaultWebOptions object, which contains global settings for how Excel handles web-related features, such as saving workbooks as web pages or interacting with web queries. Through xlwings, you can access and modify these settings to control the default behavior for web publishing, encoding, and other web-specific options. This is particularly useful when automating the generation of web content from Excel data or ensuring consistency in web output formats.

Functionality:
The DefaultWebOptions object allows you to set properties that affect web-related operations. Key properties include:

  • Encoding: Specifies the character encoding for web pages (e.g., utf-8, gb2312).
  • PixelsPerInch: Controls the screen resolution for images in web pages.
  • OrganizeInFolder: Determines whether supporting files are saved in a separate folder when saving as a web page.
  • TargetBrowser: Sets the target browser version for compatibility.
  • DownloadComponents: Specifies whether to download Office Web Components.

Syntax in xlwings:
In xlwings, you access DefaultWebOptions via the Application object. Since xlwings uses the underlying Excel object model through COM, the syntax mirrors VBA but is adapted for Python. The general format is:

app = xw.apps.active # Get the active Excel application
web_options = app.api.DefaultWebOptions

Once you have the web_options object, you can get or set its properties. For example, to set the encoding:

web_options.Encoding = "utf-8"

Note that DefaultWebOptions is a property, not a method, so it doesn’t take parameters directly. However, its properties may have specific values. For instance, TargetBrowser can be set using constants like xlBrowserV4 (for older browsers) or xlBrowserIE6 (for Internet Explorer 6). In xlwings, you can use the integer equivalents or import constants from win32com.client.constants if available.

Example Usage:
Here is a code example that demonstrates how to configure DefaultWebOptions using xlwings to prepare a workbook for web publishing. This script sets various properties and then saves the active workbook as a web page with the specified settings.

import xlwings as xw

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

# Access the DefaultWebOptions object
web_options = app.api.DefaultWebOptions

# Configure web properties
web_options.Encoding = "utf-8" # Set character encoding to UTF-8
web_options.PixelsPerInch = 96 # Set screen resolution for images
web_options.OrganizeInFolder = True # Save supporting files in a separate folder
web_options.TargetBrowser = 3 # Use constant for Internet Explorer 6 (value 3)
web_options.DownloadComponents = False # Disable downloading Office Web Components

# Save the active workbook as a web page with these settings
workbook = app.books.active
workbook.api.SaveAs(Filename="C:\\Output\\webpage.html", FileFormat=44) # FileFormat 44 is for web page

How To Create Sliding Bead Chart Using xlwings? 3

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
    ax1.HasMinorGridlines = True
    ax2.HasTitle = True
    ax2.AxisTitle.Text = 'Values'
    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

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('B2:C11').Select()  #数据
shp=sht.api.Shapes.AddChart2(-1, xw.constants.ChartType.xlXYScatter, 30, 20, 230, 380, True)
cht=shp.Chart  #添加图表

count=cht.SeriesCollection().Count
if count>0:
    for i in range(count,0,-1):
        cht.SeriesCollection(i).Delete()

cht.SeriesCollection().NewSeries()
cht.SeriesCollection(1).ChartType=xw.constants.ChartType.xlXYScatter
cht.SeriesCollection(1).XValues=sht.api.Range("B2:B11")
cht.SeriesCollection(1).Values=sht.api.Range("D2:D11")
  
cht.SeriesCollection().NewSeries()
cht.SeriesCollection(2).ChartType=xw.constants.ChartType.xlXYScatter
cht.SeriesCollection(2).XValues=sht.api.Range("C2:C11")
cht.SeriesCollection(2).Values=sht.api.Range("E2:E11")

cht.Axes(1).MinimumScale=0.04
cht.Axes(1).MaximumScale=0.28
cht.Axes(2).MinimumScale=0
cht.Axes(2).MaximumScale=21

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

The Application.DefaultSheetDirection property in Excel’s object model allows developers to set or retrieve the default direction in which new worksheets are laid out within a workbook. This property influences whether the sheet content is displayed from left-to-right (typical for languages like English) or right-to-left (common for languages such as Arabic or Hebrew). It is particularly useful in internationalized applications where the user interface must adapt to different reading orientations. In xlwings, this property can be accessed and modified through the api property of the App object, providing a programmatic way to control sheet direction directly from Python.

Syntax in xlwings:

app.api.DefaultSheetDirection

This property is both readable and writable. It accepts integer values that correspond to specific direction settings:

  • xlLTR (value: -5003): Sets the default direction to left-to-right.
  • xlRTL (value: -5004): Sets the default direction to right-to-left.

These constants are part of the Excel enumeration XlSheetDirection. In xlwings, you can use the integer values directly or import the constants from the win32com.client.constants module if working on Windows with COM support, though xlwings typically abstracts this. The property applies at the application level, meaning it affects all new workbooks and sheets created during the session until changed.

Code Examples:

  1. Reading the Current Default Sheet Direction:
import xlwings as xw
app = xw.App(visible=False)
current_direction = app.api.DefaultSheetDirection
print(f"Default sheet direction: {current_direction}") # Output: -5003 for left-to-right
app.quit()

This example retrieves the current setting, which defaults to left-to-right in most installations.

  1. Setting the Default Sheet Direction to Right-to-Left:
import xlwings as xw
app = xw.App(visible=False)
app.api.DefaultSheetDirection = -5004 # xlRTL for right-to-left
# Create a new workbook to see the effect
wb = app.books.add()
ws = wb.sheets[0]
print(f"New sheet direction set to: {app.api.DefaultSheetDirection}")
wb.save('right_to_left_sheet.xlsx')
app.quit()

After setting the property, any new worksheets will adopt the right-to-left layout, affecting text alignment and sheet navigation.

  1. Toggling Between Directions Based on User Input:
import xlwings as xw
def set_sheet_direction(direction='LTR'):
app = xw.App(visible=False)
if direction.upper() == 'RTL':
    app.api.DefaultSheetDirection = -5004
else:
    app.api.DefaultSheetDirection = -5003
    wb = app.books.add()
    print(f"Sheet direction configured for {direction}.")
app.quit()
set_sheet_direction('RTL')

How To Create Sliding Bead 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
    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
    ax1.HasMinorGridlines = True
    ax2.HasTitle = True
    ax2.AxisTitle.Text = 'Values'
    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

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('B2:C12').Select()  #数据
shp=sht.api.Shapes.AddChart2(-1, xw.constants.ChartType.xlXYScatter, 30, 20, 230, 380, True)
cht=shp.Chart  #添加图表

count=cht.SeriesCollection().Count
if count>0:
    for i in range(count,0,-1):
        cht.SeriesCollection(i).Delete()

cht.SeriesCollection().NewSeries()
cht.SeriesCollection(1).ChartType=xw.constants.ChartType.xlXYScatter
cht.SeriesCollection(1).XValues=sht.api.Range("B2:B12")
cht.SeriesCollection(1).Values=sht.api.Range("D2:D12")
  
cht.SeriesCollection().NewSeries()
cht.SeriesCollection(2).ChartType=xw.constants.ChartType.xlXYScatter
cht.SeriesCollection(2).XValues=sht.api.Range("C2:C12")
cht.SeriesCollection(2).Values=sht.api.Range("D2:D12")

cht.Axes(1).MinimumScale=0.04
cht.Axes(1).MaximumScale=0.28
cht.Axes(2).MinimumScale=0
cht.Axes(2).MaximumScale=12

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

The Application.DefaultSaveFormat property in Excel’s object model is a read/write property that determines the default file format used when saving a new workbook. This property influences the file format (e.g., .xlsx, .xls, .csv) that Excel will default to in the “Save As” dialog for a new, unsaved workbook. It does not change the format of already saved workbooks. In xlwings, this property is accessed via the Application object, allowing automation scripts to programmatically set or retrieve the default save format, ensuring consistency in file operations across automated Excel processes.

Syntax in xlwings:
The property is accessed through the app object (an instance of xlwings’ App). The syntax is straightforward, as it maps directly to the Excel object model:

  • To get the current default save format:
default_format = app.api.DefaultSaveFormat
  • To set a new default save format:
app.api.DefaultSaveFormat = format_value

Here, app refers to the xlwings App instance (e.g., app = xw.App() or xw.apps.active). The format_value is an integer corresponding to the Excel file format constant. xlwings uses the Excel object model’s constants, which can be referenced via the app.api interface. Common values include:

  • 51: xlOpenXMLWorkbook (.xlsx, without macros)
  • 52: xlOpenXMLWorkbookMacroEnabled (.xlsm, with macros)
  • 50: xlExcel12 (Excel Binary Workbook .xlsb)
  • 6: xlCSV (CSV format)
  • -4143: xlWorkbookNormal (legacy .xls format in older Excel versions)
    These constants are part of the Excel enumeration XlFileFormat. In xlwings, you can use the integer values directly or, for clarity, define them as variables (e.g., xlOpenXMLWorkbook = 51). Note that the property is specific to the Excel application instance, so changes apply to all workbooks under that instance.

Examples:
Below are practical xlwings API code examples demonstrating how to use the DefaultSaveFormat property.

  1. Retrieving the Current Default Save Format:
    This example connects to the active Excel instance and prints the current default save format.
import xlwings as xw

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

# Get the default save format
current_format = app.api.DefaultSaveFormat
print(f"Current default save format value: {current_format}")

Output might show an integer like 51, indicating .xlsx is the default.

  1. Setting the Default Save Format to .xlsm:
    This example sets the default save format to Excel Macro-Enabled Workbook (.xlsm) for new workbooks.
import xlwings as xw

# Start a new Excel instance (or use active)
app = xw.App(visible=False) # Run in background

# Define the format value for .xlsm
xlOpenXMLWorkbookMacroEnabled = 52

# Set the default save format
app.api.DefaultSaveFormat = xlOpenXMLWorkbookMacroEnabled

# Verify the change
print(f"Default save format set to: {app.api.DefaultSaveFormat}")

# Clean up: close the app without saving
app.quit()

After running this, any new workbook created in this Excel instance will default to .xlsm when saved for the first time.

  1. Using DefaultSaveFormat in a Workflow:
    This example integrates DefaultSaveFormat into a script that creates a workbook and saves it, leveraging the default format.
import xlwings as xw

# Launch Excel and set default to CSV for data export tasks
app = xw.App(visible=True)
app.api.DefaultSaveFormat = 6 # xlCSV

# Add a new workbook
wb = app.books.add()
sheet = wb.sheets[0]
sheet.range('A1').value = [['Data', 'Value'], [1, 100], [2, 200]]

# Save the workbook; it will default to CSV in the Save As dialog
# Note: This property doesn't auto-save; it sets the dialog default.
wb.save('new_data') # User may see .csv as default in the dialog

# Close
wb.close()
app.quit()