使用openpyxl创建Excel图表

tamoadmin 赛事报道 2024-04-26 12 0

要使用`openpyxl`创建Excel图表,你可以遵循以下步骤:

1.导入必要的库:

```python

from

openpyxl

import

Workbook

from

openpyxl.chart

import

(

BarChart,

Reference,

Series,

)

```

2.创建一个`Workbook`对象:

```python

workbook

=

Workbook()

```

3.选择或创建一个工作表:

```python

worksheet

=

workbook.active

```

4.在工作表中填写一些数据,这些数据将用于创建图表:

```python

data

=

[

['Category',

'Value'],

['Item

1',

10],

['Item

2',

20],

['Item

3',

30],

['Item

4',

40],

['Item

5',

50],

]

for

row

in

data:

worksheet.append(row)

```

5.创建一个图表:

```python

chart

=

BarChart()

chart.title

=

"My

Chart"

chart.width

=

4

chart.height

=

3

```

6.设置图表的数据源:

```python

data_range

=

Reference(worksheet,

min_row=1,

max_row=6,

min_col=1,

max_col=2)

series

=

Series(

title="Series

1",

values=data_range,

)

chart.add_series(series)

```

7.将图表添加到工作表中:

```python

worksheet.add_chart(chart,

'E2')

```

8.保存工作簿:

```python

workbook.save("chart_example.xlsx")

使用openpyxl创建Excel图表

```

完整的代码示例:

```python

from

openpyxl

import

Workbook

from

openpyxl.chart

import

(

BarChart,

Reference,

Series,

)

workbook

=

Workbook()

worksheet

=

workbook.active

data

=

[

['Category',

'Value'],

['Item

1',

10],

['Item

2',

20],

['Item

3',

30],

['Item

4',

40],

['Item

5',

50],

]

for

row

in

data:

worksheet.append(row)

chart

=

BarChart()

chart.title

=

"My

Chart"

chart.width

=

4

chart.height

=

3

data_range

=

Reference(worksheet,

min_row=1,

max_row=6,

min_col=1,

max_col=2)

series

=

Series(

title="Series

1",

values=data_range,

)

chart.add_series(series)

worksheet.add_chart(chart,

'E2')

workbook.save("chart_example.xlsx")

使用openpyxl创建Excel图表

```

这个例子创建了一个简单的条形图,并将其添加到了名为`chart_example.xlsx`的工作簿中。你可以根据需要修改数据、图表类型和样式,以满足你的具体要求。