Thursday, May 12, 2022

[FIXED] How to append columns instead of rows openpyxl?

Issue

Currently using Openpyxl. I understand that append will print the output in excel in rows. I am trying to figure out if there is a function that can print the output in columns .eg:

headings = ['Name','Fruits']
ws.append(headings)

Name = ['John','Ben','Lily','Sarah']
Fruits = ['Orange','Apple','Grape','Peach']

Output in excel:

    A         B
 1 Name     Fruits
 2 John     Orange
 3 Ben      Apple
 4 Lily     Grape
 5 Sarah    Peach

Solution

The information you are looking for is shown here. The example shows how to iterate over columns and rows, which just ends up being simple grid/matrix logic.

from itertools import cycle

c = cycle([1, 2])

for idx in range(len(Name)):
    ws.cell(column=next(c), row=idx, value=Name[idx])
    ws.cell(column=next(c), row=idx, value=Fruits[idx])

# Column 1, Row 0 John
# Column 2, Row 0 Orange
# Column 1, Row 1 Ben
# Column 2, Row 1 Apple
# etc...


Answered By - gold_cy
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.