You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# pip install pywin32
# https://blog.csdn.net/weixin_42927998/article/details/115086797
import win32com
from win32com.client import Dispatch
docApp = win32com.client.Dispatch('Word.Application')
docApp.Visible = True
docApp.DisplayAlerts = 0
doc = docApp.Documents.Open('c:/1.docx')
# 创建图表图表的插入位置为预先在word文档中插入的书签书签名为“插入图表位置”
shape_chart = doc.Shapes.AddChart2(Style=201, Type=51, Top=doc.Bookmarks("插入图表位置").Select())
shape_chart.WrapFormat.Type = 7 # 设置图表为嵌入型
# 设置Word中的图表
chart = shape_chart.Chart
# 图表数据对应的工作表
worksheet = chart.ChartData.Workbook.Worksheets(1)
chart.SetSourceData("Sheet1!$A$1:$C$4") # 设置数据源范围
# 簇状柱形图测试数据
chart_data = [["", "系列A", "系列B", "系列C", "系列D"],
[2020, 2, 4, 2, 3],
[2019, 4, 5, 3, 2]]
# 清空工作表默认数据
worksheet.Range("A1:D5").value = None
# 填入测试数据
for row_index, row in enumerate(chart_data):
for column_index, value in enumerate(row):
worksheet.Cells(row_index + 1, column_index + 1).Value = value
chart.SetSourceData("Sheet1!$A$1:$E$3") # 设置数据源范围
# 设置图表样式示例
chart.ChartTitle.Text = '测试标题' # 设置标题
chart.FullSeriesCollection(2).Format.Fill.ForeColor.ObjectThemeColor = 10 # 设置系列2的填充颜色
chart.ChartData.Workbook.Close() # 关闭workbook窗口
doc.Save()
doc.Close()
docApp.Quit()
'''
Type
1柱形图Column
2折线图Line
3饼图Pie
51堆叠柱形图Stacked Column
52堆叠线图Stacked Line
53堆叠区域图Stacked Area
55雷达图Radar
65树状图Treemap
73旭日图Sunburst
77水桶图Funnel
109散点图Scatter
183气泡图Bubble
'''