udaykls
udaykls

Reputation: 39

Table in Python docx

Here its printing sunday in all the cells in the table

docu = docx.Document()

daylist = ["monday", "tuesday", "wednesday",
           "thursday", "friday", "saturday", "sunday"]

num_of_days = int(input('enter days'))
num_of_lectures = int(input('lecture number'))

timetable = docu.add_table(rows=num_of_days, cols=num_of_lectures)
tablecell = timetable.cell(0, 1)
tablerow = timetable.rows[1]

for day in daylist:
    for tablerow in timetable.rows:
        for tablecell in tablerow.cells:
            tablecell.text = day

docu.save('timetable.docx')

and if I'm doing this it's printing the whole list in each cell.

docu = docx.Document()

daylist = ["monday", "tuesday", "wednesday",
           "thursday", "friday", "saturday", "sunday"]

num_of_days = int(input('enter days'))
num_of_lectures = int(input('lecture number'))

timetable = docu.add_table(rows=num_of_days, cols=num_of_lectures)
tablecell = timetable.cell(0, 1)
tablerow = timetable.rows[1]

for tablerow in timetable.rows:
    for tablecell in tablerow.cells:
        tablecell.text = (day for day in daylist)

docu.save('timetable.docx')

and I've tried

daylist = ["monday", "tuesday", "wednesday",
           "thursday", "friday", "saturday", "sunday"]

num_of_days = int(input('enter days'))
num_of_lectures = int(input('lecture number'))

timetable = docu.add_table(rows=num_of_days, cols=num_of_lectures)
tablerow = timetable.rows[1]

i = 0
for cells in timetable.rows:
    i += 1
    tablecell = timetable.cell(i, 0)
    cells.text = (day for day in daylist)

docu.save('timetables.docx')

I need one string from daylist list in only top row. Python docx documentation is difficult to understand.

Upvotes: 0

Views: 329

Answers (2)

scanny
scanny

Reputation: 28893

The Python code is faithfully doing what you are asking it to do. Perhaps you are confused about how iteration works.

I'm assuming you want a result that looks like this:

+--------+---------+-----------+
| Monday | Tuesday | Wednesday |
+--------+---------+-----------+
|        |         |           |
+--------+---------+-----------+
|        |         |           |
+--------+---------+-----------+

This can be accomplished a variety of ways, but something like this would do the trick:

cells = table.rows[0].cells
for i in num_of_days:
   cells[i].text = daylist[i]

or perhaps better:

for i, cell in enumerate(table.rows[0].cells):
    cell.text = daylist[i]

slightly fancier would be:

for cell, title in zip(table.rows[0].cells, daylist):
    cell.text = title

Upvotes: 2

Simon Crane
Simon Crane

Reputation: 2182


import itertools

tablerow = timetable.rows[0]

for (day, cell) in zip(itertools.cycle(daylist), tablerow):
    cell.text = day

Upvotes: 0

Related Questions