简体   繁体   中英

put data on excel with openpyxl

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "sheet"

grade = ["A","B","C","D","E","F","G","H","I","J","K"]

for lst in grade:
    for i in range(len(grade)):
        ws.cell(row=i+1, column=1, value=lst)

wb.save("list.xlsx")

in this case, i expect the data should be arrayed like [image1]. but the result is [image2]. i dont know what is wrong with my code.. Thank you. enter image description here enter image description here

I think this is what you want, my friend:

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "sheet"

grade = ["A","B","C","D","E","F","G","H","I","J","K"]

for i in range(len(grade)):
    ws.cell(row=i+1, column=1, value=grade[i])

wb.save("list.xlsx")

The problem here is that when you step in the second for loop where you pu your grade into each cell, the value of i changes. You can use global variable for row count this way your rows won't be overwritten.

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