I am doing a exercise sheet in Excel using openpyxl.
It is for my daughter to use for exercise multiplication tables.
So far everything is good. I got everything working as I want to. I also added code to set width and height of the cells.
However when I set a width for column “A” it affects also columns “B”, “C” and “D”.
But column “E” is not affected. It can be set individually
This “behaviour” repeat it self at columns “F” to “I”
Why is three other columns affected by one?
from random import randint
from openpyxl import Workbook
from openpyxl import load_workbook
# wb = Workbook()
# Used when creating a new file
wb = load_workbook("multitest.xlsx")
ws = wb.active
# slump = random
def slump_a():
a = randint(6,9)
return a
def slump_b():
b = randint(1,10)
return b
for i in range(1, 31):
ws.cell(row=i, column=1, value=slump_a())
ws.cell(row=i, column=2, value="x")
ws.cell(row=i, column=3, value=slump_b())
ws.cell(row=i, column=4, value="=")
ws.cell(row=i, column=5, value="___")
ws.cell(row=i, column=6, value=slump_a())
ws.cell(row=i, column=7, value="x")
ws.cell(row=i, column=8, value=slump_b())
ws.cell(row=i, column=9, value="=")
ws.cell(row=i, column=10, value="___")
ws.column_dimensions['A'].width = 4
# Above also set width for column B, C, and D. (!?)
ws.column_dimensions['E'].width = 12
ws.column_dimensions['F'].width = 4
# Above also set width for column G, H, and I. (!?)
ws.column_dimensions['J'].width = 12
# row_dimensions
# rader = rows, rad = row
rader = ws.max_row + 1
for rad in range(1, rader):
ws.row_dimensions[rad].height = 20
wb.save("multitest.xlsx")
Output looks like:
6 x 9 = __ 7 x 3 = __
9 x 3 = __ 9 x 4 = __
and so on for 15 rows
Total of 30 questions.
I could not wait until I got home. And I wanted to try on a Windows machine also.
At home I have got Ubuntu and Libre office. I will try the same when I got home.
It worked At least at work.
I am a bit ashamed to say, but I think you are wrong about
ws.cell(row=i, column=1, value=slump_a())
When one use the cell function one set the row and column by number + the value to fill the cell with.
There is another way to set the value of a cell:
ws[“A1”] = "hello!
Now its time to go home and try this on my Linux machine.
I will report the outcome of that later.