【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
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:B7').value
app.kill()
from comtypes.client import CreateObject
app2=CreateObject("Excel.Application")
app2.Visible=True
app2.ScreenUpdating=False
wb2=app2.Workbooks.Open(root+r'/data.xlsx')
sht2=wb2.Sheets('Sheet1')
shp=sht2.Shapes.AddChart2()
shp.Left=20
cht=shp.Chart
cht.ChartType=-4169
ax1=cht.Axes(1)
ax2=cht.Axes(2)
ax1.MinimumScale=0
ax1.MaximumScale=7
ax2.MinimumScale=0
ax2.MaximumScale=0.22
set_style(cht)
cht.SeriesCollection().NewSeries()
pt=[[0 for _ in range(2)] for _ in range(4)]
for i in range(6):
pt[0][0]=shape_x(cht,i+1-0.25)
pt[0][1]=shape_y(cht,data[i][1])
pt[1][0]=shape_x(cht,i+1)
pt[1][1]=shape_y(cht,0)
pt[2][0]=shape_x(cht,i+1+0.25)
pt[2][1]=shape_y(cht,data[i][1])
pt[3][0]=pt[0][0]
pt[3][1]=pt[0][1]
shp=cht.Shapes.AddPolyline(pt)
shp.Fill.ForeColor.RGB=xw.utils.rgb_to_int((255,192,0))
shp.Fill.TwoColorGradient(2,1)
shp.Fill.BackColor.RGB=xw.utils.rgb_to_int((240,240,240))
shp.Line.Visible=False
x=shape_x(cht,i+1-0.35)
y=shape_y(cht,data[i][1]+0.025)
w=cht.PlotArea.InsideWidth/(ax1.MaximumScale-ax1.MinimumScale)*1
h=cht.PlotArea.InsideHeight/(ax2.MaximumScale-ax2.MinimumScale)*0.04
shp2=cht.Shapes.AddLabel(1,x,y,w,h)
shp2.TextFrame.Characters().Text=str(data[i][1])
shp2.TextFrame.Characters().Font.Color=xw.utils.rgb_to_int((0,0,0))
shp2.TextFrame.Characters().Font.Size=8
app2.ScreenUpdating=True
#wb2.Save()
#os.system('taskkill /f /im EXCEL.EXE')

Leave a Reply