openpyxl绘制折线图
时间: 2023-12-17 17:27:30 浏览: 86
以下是使用openpyxl绘制折线图的步骤:
1.导入openpyxl和openpyxl.chart模块
```python
import openpyxl
from openpyxl.chart import LineChart, Reference
```
2.打开Excel文件并选择工作表
```python
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb['Sheet1']
```
3.创建一个LineChart对象
```python
chart = LineChart()
```
4.设置LineChart对象的样式和属性
```python
chart.title = '利润走势图'
chart.x_axis.title = '日期'
chart.y_axis.title = '利润'
```
5.创建一个Reference对象,用于指定数据范围
```python
data = Reference(sheet, min_col=2, min_row=2, max_col=3, max_row=7)
```
6.将Reference对象添加到LineChart对象中
```python
chart.add_data(data)
```
7.将LineChart对象添加到工作表中
```python
sheet.add_chart(chart, 'E2')
```
完整代码如下:
```python
import openpyxl
from openpyxl.chart import LineChart, Reference
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb['Sheet1']
chart = LineChart()
chart.title = '利润走势图'
chart.x_axis.title = '日期'
chart.y_axis.title = '利润'
data = Reference(sheet, min_col=2, min_row=2, max_col=3, max_row=7)
chart.add_data(data)
sheet.add_chart(chart, 'E2')
wb.save('example.xlsx')
```
阅读全文