简体   繁体   中英

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

  • Text 1
  • Text 2
  • Text 3

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

  • A1 = Text 1 Text 2 Text 3

What I want

  • A1 = Text 1
  • A2 = Text 2
  • A3 = Text 3

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM