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.
|
|
|
|
# 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)
|
|
|
|
|
'''
|