I currently have a simple list containing integers: amounts = [5, 10, 15]
. I would like to write these values into Excel cells, without having to type out statements for each element. At the moment, I have the following code which writes all elements of the list, but without iteration and instead with individual statements.
import openpyxl
from openpyxl import load_workbook
amounts = [5, 10, 15]
book = load_workbook("output.xlsx")
sheet = book.active
sheet["A2"] = amounts[0]
sheet["B2"] = amounts[1]
sheet["C2"] = amounts[2]
print ("done")
book.save("output.xlsx")
I understand I can define a cell range by doing this; cells = sheet["A2":"C2"]
. How can I use cells
and amounts
together to iterate with each other, so that I can assign amounts[0]
to A2
, amounts[1]
to B2
, and so on. This list is bigger in reality, just made it smaller for question's sake.
You can set value into cell using method cell
from openpyxl import Workbook
amounts = [5, 10, 15]
book = Workbook()
sheet = book.active
row = 2
for i, value in enumerate(amounts):
sheet.cell(column=i+1, row=row, value=value)
print("done")
book.save("output.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.