How to add the Data into the existing Chart dynamically using openpyxl - python

I am trying add the Data into the existing Line Chart dynamically when new data comes in into the excel using openpyxl. Below is the sample code I tried But when else part is encountered there is no changes in the chart.
Thanks
from openpyxl import load_workbook
from openpyxl.chart import (LineChart, Reference)
wb = load_workbook("Hello.xlsx")
sheet = wb.active
exists = 0
chart = LineChart()
if exists == 1:
values = Reference(sheet, min_col=3, min_row=1, max_row=sheet.max_row)
categories = Reference(sheet, min_col=1, min_row=2, max_row=sheet.max_row,max_col=1)
chart.add_data(values, titles_from_data=True)
chart.set_categories(categories)
chart.title = "sample"
chart.x_axis.title = "date"
chart.y_axis.title = "followers"
sheet.add_chart(chart, "F2")
else:
values_update = Reference(sheet, min_col=3, min_row=1, max_row=sheet.max_row)
chart.add_data(values_update)
wb.save("Hello.xlsx")

Related

How to group the x_axis dates in openpyxl

I want to group the x_axis (Date) so that if there is a cell with 01/01/2022 & another 01/01/2022 it will only show one bar with 01/01/2022, here it actualy print each row with a bar
How can i do that in openpyxl please
Thanks in advance
from openpyxl import Workbook
from openpyxl.chart import BarChart, Series, Reference
wb = Workbook(write_only=True)
ws = wb.create_sheet()
rows = [
('Date', 'Batch 1'),
(01/01/2022, 10),
(01/01/2022, 40),
(02/01/2022, 50),
(04/01/2022, 20)
]
for row in rows:
ws.append(row)
chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "Bar Chart"
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'
data = Reference(ws, min_col=2, min_row=1, max_row=5, max_col=2)
cats = Reference(ws, min_col=1, min_row=2, max_row=5)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")
So you want a stacked chart like this then?
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
rows = [
('Date', 'Batch 1', 'Batch 2'),
('01/01/2022', 10, 40),
('02/01/2022', 50, ''),
('04/01/2022', 20, '')
]
wb = Workbook(write_only=True)
ws = wb.create_sheet()
for row in rows:
ws.append(row)
chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "Bar Chart"
chart1.grouping = "stacked" # Stacked column chart
chart1.overlap = 100 # Set overlap to 100% so top column sits squarely on the bottom column
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'
data = Reference(ws, min_col=2, min_row=1, max_row=4, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=4)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")
wb.save('new_chart1.xlsx')

How to make labels visible inside the pie in openpyxl

I automate some task with openpyxl with xlsx file, i created a piechart but i want the piechart to show the labels and not only the value ( got exemple apple, cherry… will be in text inside the pie is there a way to do that with openpyxl ?
Thanks
from openpyxl import Workbook
from openpyxl.chart import (
PieChart,
ProjectedPieChart,
Reference
)
from openpyxl.chart.series import DataPoint
data = [
['Pie', 'Sold'],
['Apple', 50],
['Cherry', 30],
['Pumpkin', 10],
['Chocolate', 40],
]
wb = Workbook()
ws = wb.active
for row in data:
ws.append(row)
pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"
Do you want to do something like this where name and percent is marked on the segments?
from openpyxl import Workbook
from openpyxl.chart.label import DataLabelList
from openpyxl.chart import (
PieChart,
Reference
)
data = [
['Pie', 'Sold'],
['Apple', 50],
['Cherry', 30],
['Pumpkin', 10],
['Chocolate', 40],
]
wb = Workbook()
ws = wb.active
for row in data:
ws.append(row)
pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"
### Add Label into chart
pie.dataLabels = DataLabelList()
pie.dataLabels.showPercent = True
pie.dataLabels.showCatName = True
ws.add_chart(pie, "A10")
wb.save('test_chart.xlsx')
It should produce a chart like

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. Is it possible to build a chart using openpyxl with this data that already exists in these cells? 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")

Openpyxl not showing second graph

EDIT: Solved, solution in answer below.
I have a graph created with openpyxl that has two y axes sharing a DateAxis. Although the first selection of data is showing on the graph, the second isn't. There's also a strange gray line on the bottom of the graph that wasn't there before. I think it's just a small error I'm missing somewhere, but I can't see where. Especially considering I have my range of cells defined correctly. What could I be doing wrong?
import openpyxl
from openpyxl import Workbook, chart
from openpyxl.chart import LineChart, Reference, Series
from openpyxl.chart.axis import DateAxis
from datetime import date, datetime, timedelta, time
ws2 = wb['sheet2']
dates = chart.Reference(ws2, min_col=1, min_row=2, max_row=sheet.max_row)
vBat = chart.Reference(ws2, min_col=2, min_row=1, max_col=2, max_row=sheet.max_row)
qBat = chart.Reference(ws2, min_col=3, min_row=1, max_col=3)
c1 = chart.LineChart()
c1.title = "SLA Discharge - 5.5A: V_BAT"
c1.style = 12
c1.x_axis.majorTimeUnit = "days"
c1.x_axis = chart.axis.DateAxis()
c1.x_axis.title = "Time"
c1.x_axis.crosses = "min"
c1.x_axis.majorTickMark = "out"
c1.x_axis.number_format = 'd-HH-MM-SS'
c1.add_data(vBat, titles_from_data=True)
c1.set_categories(dates)
c1.y_axis.title = "Battery Voltage"
c1.y_axis.crossAx = 500
c1.y_axis.majorGridlines = None
c2 = chart.LineChart()
c2.x_axis.axId = 500 # same as c1
c2.add_data(qBat, titles_from_data=True, from_rows=True)
c2.set_categories(dates)
c2.y_axis.axId = 200
c2.y_axis.title = "Qbat Percentage"
c2.y_axis.crossAx = 500
c1.y_axis.crosses = "max"
c1 += c2
s1 = c1.series[0]
s1.graphicalProperties.line.solidFill = "BE4B48"
s1.graphicalProperties.line.width = 25000 # width in EMUs.
s1.smooth = True # Make the line smooth
s2 = c2.series[0]
s2.graphicalProperties.line.solidFill = "48BBBE"
s2.graphicalProperties.line.width = 25000 # width in EMUs.
s2.smooth = True # Make the line smooth
ws2.add_chart(c1, "D5")
Interestingly enough,
vBat = chart.Reference(ws2, min_col=2, min_row=1, max_col=2, max_row=sheet.max_row)
is fine. However, doing the same thing to qBat with:
qBat = chart.Reference(ws2, min_col=3, min_row=1, max_col=3, max_row=sheet.max_row)
"corrupts" the workbook and displays an error message upon opening and doesn't print any chart. Removing max_row=sheet.max_row from both lines produces an incorrect DateAxis where there are only two points and they're both the first two values in the time column.
first, in c2.add_data(qBat, titles_from_data=True, from_rows=True), remove from_rows=True.
Then, change qBat to:
qBat = chart.Reference(ws2, min_col=3, min_row=1, max_col=3, max_row=sheet.max_row)

how to make a list from result of a function?

When I run my code it works very well and makes an excel file I named exel.xlsx, but there is no information in exel.xlsx.
I think I make a mistake in making a list but I can't find a solution.
def randStr(length=7):
characters = list('bcdghijkmnpqrtuvwxyz23456789')
shuffle(characters)
exel = ''.join(characters[:length])
listb = [exel]
listb.append(exel)
workbook = xlsxwriter.Workbook('Exel.xlsx')
worksheet = workbook.add_worksheet('randomise')
chart = workbook.add_chart({'type': 'line'})
expenses = (listb)
row = 0
col = 0
workbook.close()
return exel
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_line.xlsx')
worksheet = workbook.add_worksheet()
# Add the worksheet data to be plotted.
data = [10, 40, 50, 20, 10, 50]
worksheet.write_column('A1', data)
# Create a new chart object.
chart = workbook.add_chart({'type': 'line'})
# Add a series to the chart.
chart.add_series({'values': '=Sheet1!$A$1:$A$6'})
# Insert the chart into the worksheet.
worksheet.insert_chart('C1', chart)
workbook.close()
This is the basic way to add_chart , then adding the values to chart and inserting the chart .
But you are not adding any value to your chart. Moreover you are not adding any value to the column/row in sheet.
I ran your code , sheet with name "randomise" is created , but no data in it, as you havent added anything
solved!
def randStr(length=7):
characters = list('bcdghijkmnpqrtuvwxyz23456789')
shuffle(characters)
listc=''.join(characters[:length])
return listc
listb=[]
if __name__ == '__main__':
for i in range(20):
value1=(randStr())
listb.append(value1)
workbook = xlsxwriter.Workbook('Exel.xlsx')
worksheet = workbook.add_worksheet('randomise')
worksheet.write_column(0,0,listb)
chart = workbook.add_chart({'type': 'line'})
expenses =(listb)
row = 0
col = 0
workbook.close()
img = makeImage(value1, width=512)
with open('%d.png' % i, 'wb') as f:
f.write(img)
print (i)

Categories