Python - 使用 openpyxl 模块在 excel 表中绘制图表

pythonserver side programmingprogramming

Openpyxl 是一个 Python 库,使用它可以在 excel 文件上执行多种操作,如读取、写入、算术运算和绘制图形。

示例

# 导入 o​​penpyxl 模块
import openpyxl
#从 openpyxl.chart 导入 BubbleChart、Reference、Series 类 #sub_module
从 openpyxl.chart 导入 BubbleChart、Reference、Series
# 调用 openpyxl 的 Workbook() 函数创建一个新的空白 #Workbook 对象
wb = openpyxl.Workbook()
# 从 active 属性获取工作簿活动表。
sheet = wb.active
rows = [
   ("产品数量", "美元销售额", "市场份额"),
   (14, 12200, 15),
   (20, 60000, 33),
   (18, 24400, 10),
   (22, 32000, 42),
]
#分别在活动工作表的第 1、2 和 3 列中写入每行的内容。
for row in rows:
   sheet.append(row)
# 创建 BubbleChart 类的对象
chart = BubbleChart()
# 创建绘图数据
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)
# 创建第一系列数据
series = Series(values = yvalues, xvalues = xvalues, zvalues = size, title ="2013")
# 将系列数据添加到图表对象
chart.series.append(series)
# 设置图表标题
chart.title = " BUBBLE-CHART "
# 设置 x 轴的标题
chart.x_axis.title = " X_AXIS "  
# 设置 y 轴的标题
chart.y_axis.title = " Y_AXIS "
# 将图表添加到工作表图表的左上角
# 锚定到单元格 E2
sheet.add_chart(chart, "E2")  
# 保存文件
wb.save("bubbleChart.xlsx")

相关文章