Xyltic
Xyltic

Reputation: 123

For loop Python OpenPyXL in Excel

Context

Got a variable Output that contains text mentioned below. However, I want to insert each Output line on each A-row in Excel. How do I do this?

Output

Current Code

# Open Workbook
wb = load_workbook('Fortimail-config.xlsx')
ws = wb.active

# Create a workbook sheet name.
sheet = wb['Sheet']

sheet.cell(row=1, column=1).value = output

wb.save("Fortimail-config.xlsx")

What I get

What I want

Upvotes: 0

Views: 391

Answers (1)

Greg
Greg

Reputation: 4518

sheet.cell(row=1, column=1).value = output here the code is assigning value to row 1 and column 1. Therefore this will map to excel cell A1

Assuming output variable is an array; you can append it to the sheet using sheet.append() and it will add the array to each row.

For example:

output = ['Text 1', 'Text 2', 'Text 3']

wb = load_workbook('Fortimail-config.xlsx')
ws = wb.active

# Create a workbook sheet name.
sheet = wb['Sheet']

sheet.append(output)

wb.save("Fortimail-config.xlsx")

Upvotes: 1

Related Questions