Openpyxl là một thư viện Python cho phép thực hiện nhiều thao tác trên file Excel như đọc, ghi, phép toán và vẽ đồ thị.
Ví dụ
# import module openpyxl
import openpyxl
# import BubbleChart, Reference, Series class từ
# sub_module openpyxl.chart
from openpyxl.chart import BubbleChart, Reference, Series
# Gọi hàm Workbook() của openpyxl để tạo một đối tượng
# Workbook trống mới
wb = openpyxl.Workbook()
# Lấy worksheet active từ thuộc tính active.
sheet = wb.active
rows = [
("Number of Products", "Sales in USD", "Market share"),
(14, 12200, 15),
(20, 60000, 33),
(18, 24400, 10),
(22, 32000, 42),
]
# ghi nội dung của mỗi hàng vào cột 1, 2, 3 của active sheet tương ứng.
for row in rows:
sheet.append(row)
# Tạo đối tượng lớp BubbleChart
chart = BubbleChart()
# tạo dữ liệu cho vẽ
xvalues = Reference(sheet, min_col=1, min_row=2, max_row=5)
yvalues = Reference(sheet, min_col=2, min_row=2, max_row=5)
size = Reference(sheet, min_col=3, min_row=2, max_row=5)
# tạo series dữ liệu thứ nhất
series = Series(values=yvalues, xvalues=xvalues, zvalues=size, title="2013")
# thêm series dữ liệu vào đối tượng biểu đồ
chart.series.append(series)
# đặt tiêu đề biểu đồ
chart.title = "BUBBLE-CHART"
# đặt tiêu đề trục x
chart.x_axis.title = "X_AXIS"
# đặt tiêu đề trục y
chart.y_axis.title = "Y_AXIS"
# thêm biểu đồ vào sheet, góc trên bên trái
# của biểu đồ được neo vào ô E2
sheet.add_chart(chart, "E2")
# lưu file
wb.save("bubbleChart.xlsx")