I am creating a table using the python module reportlab. In this table, I would like to loop through and have a different background color depending on the values of any particular cell.
To do this, I came up with the following:
elements = []
table1 = [[34,27,35,35],
[3,76,23,157],
[13,137,15,75],
[56,26,46,26]]
t1 = Table(table1)
for ii in range(len(table1)):
for jj in range(len(table1)):
if table1[ii][jj] <=50:
ourcolor = colors.white
elif table1[ii][jj] <=100:
ourcolor = colors.skyblue
elif table1[ii][jj] <=200:
ourcolor = colors.green
else:
ourcolor = colors.white
t1.setStyle(TableStyle([('BACKGROUND', (ii,jj), (ii,jj), ourcolor),
('ALIGN', (0,0), (-1,-1), 'CENTER'),
('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black)
]))
elements.append(t1)
But, many of the cells still are not colored and many of them are colored incorrectly, however some of them are correct. I am assuming something is wrong with my loop since I am not a very experienced programmer.
Any help or ideas would be greatly appreciated.
I don't know enough about ReportLab to know for sure, but a common problem in this type of coding is that the axes are swapped. For example, indexing like this: table1[ii][jj]
means that ii
is the y axis (rows) and jj
is the x axis (columns), so you'd have to supply x and y to ReportLab as jj, ii
. Check if your output has rows and columns swapped when coloring cells.
Also, note that your double loop is looping over the same range twice, which works only because your table is square. If your table even becomes non-square, you'll have the wrong range on one of your loops.