word中生成图表python
时间: 2023-09-26 13:11:16 浏览: 61
在Word中生成图表需要使用Python的第三方库python-docx和matplotlib。
1. 安装python-docx和matplotlib库
```
pip install python-docx
pip install matplotlib
```
2. 创建Word文档
```python
from docx import Document
document = Document()
```
3. 添加一个图表
```python
from docx.shared import Inches
from docx.enum.chart import XL_CHART_TYPE
# 添加一个图表
chart = document.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, Inches(1), Inches(1), Inches(4), Inches(3.5))
```
4. 使用matplotlib创建数据和图表
```python
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
x = np.arange(10)
y = np.random.randint(1, 10, size=10)
# 创建图表
plt.bar(x, y)
# 将图表保存为临时文件
plt.savefig('chart.png')
```
5. 将matplotlib生成的图表添加到Word中
```python
from docx.shared import Inches
# 将matplotlib生成的图表添加到Word中
chart.add_picture('chart.png', width=Inches(4), height=Inches(3.5))
```
6. 保存Word文档
```python
document.save('chart.docx')
```
完整代码:
```python
from docx import Document
from docx.shared import Inches
from docx.enum.chart import XL_CHART_TYPE
import matplotlib.pyplot as plt
import numpy as np
# 创建Word文档
document = Document()
# 添加一个图表
chart = document.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, Inches(1), Inches(1), Inches(4), Inches(3.5))
# 创建数据
x = np.arange(10)
y = np.random.randint(1, 10, size=10)
# 创建图表
plt.bar(x, y)
# 将图表保存为临时文件
plt.savefig('chart.png')
# 将matplotlib生成的图表添加到Word中
chart.add_picture('chart.png', width=Inches(4), height=Inches(3.5))
# 保存Word文档
document.save('chart.docx')
```