简体   繁体   English

是否可以引用现有数据来使用 openpyxl 创建图表?

[英]Is it is possible to reference existing data to create a chart using openpyxl?

I have some data that is already in an xlsx sheet.我有一些数据已经在 xlsx 工作表中。 Is it possible to build a chart using openpyxl with this data that already exists in these cells?是否可以使用这些单元格中已经存在的数据使用 openpyxl 构建图表? The data gets updated monthly.数据每月更新一次。

data数据

category    3/1/2021    3/8/2021
computer    2646        3000
network     117         200
other       316         20
total       3079        3220

在此处输入图像描述

Desired:期望:

A chart month by month chart next to the data数据旁边的逐月图表

在此处输入图像描述

Doing:正在做:

from datetime import date

from openpyxl import Workbook
from openpyxl.chart import (
    LineChart,
    Reference,
)
from openpyxl.chart.axis import DateAxis

wb = Workbook()
ws = wb.active



c2 = LineChart()
c2.title = "Date Axis"
c2.style = 12
c2.y_axis.title = "Size"
c2.y_axis.crossAx = 500
c2.x_axis = DateAxis(crossAx=100)
c2.x_axis.number_format = 'd-mmm'
c2.x_axis.majorTimeUnit = "days"
c2.x_axis.title = "Date"

c2.add_data(data, titles_from_data=True)
dates = Reference(ws, min_col=1, min_row=2, max_row=5)
c2.set_categories(dates)

ws.add_chart(c2, "E1")

Any suggestion is appreciated任何建议表示赞赏

#pull in your data
wb_obj = load_workbook(path)
sheet_obj = wb_obj.active

c1 = BarChart()
c1.title = "Test"
c1.y_axis.title = "Test1"
c1.x_axis.title = "Test2"

#reference your data
data = Reference(sheet_obj, min_col=2, min_row=2, max_col=3, max_row=5)
c1.add_data(data, titles_from_data=True)

#save the data
sheet_obj.add_chart(c1, "E1")
wb_obj.save("samples.xlsx")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM