1.簡介:
openpyxl不僅提供了將數據一行列的形式對應到Excel表格中,以及相關的添加,刪除,獲取等操作; 還提供了將數據進行圖形化展示的相關組件(類),包括2D圖形和3D圖形。
2.舉例:
將數據在excel中進行3D圖形化展示(例:公司近幾年銷售額和利潤的數據圖形化(3D)):
相關代碼如下:
openxls_3d_chart.py:
# -*- coding: utf-8 -*-
import os
import sys
from openpyxl import Workbook
from openpyxl.chart import BarChart3D, Series, Reference
#初始化Workbook
wb = Workbook(write_only=True)
ws = wb.create_sheet()
#創建數據
rows = [
('', '銷售額','利潤'),
(2016, 20, 8),
(2017, 30, 12),
(2018, 50, 20),
(2019, 60, 25),
(2020, 70, 35),
(2021, 80, 40),
]
#添加數據到excel
for row in rows:
ws.append(row)
#chart圖的生成1
chart1 = BarChart3D()
chart1.title = "近幾年營業額/利潤對比圖"
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
titles = Reference(ws, min_col=1, min_row=2, max_row=7)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(titles)
ws.add_chart(chart1, "A10")
#保存文件
wb.save("bar_3d.xlsx")
運行結果:
python3 openxls_3d_chart.py
生成了 bar_3d.xlsx,文件內容如下:
說明:
(1)BarChart3D:用於創建3D柱狀圖;
(2)Workbook相關操作:
wb = Workbook(write_only=True)
ws = wb.create_sheet()wb.save("bar_3d.xlsx"):保存excel表格。