简体   繁体   English

如何使用openpyxl使用列表写入Excel单元格区域?

[英]How can I use a list to write into an Excel cell range using openpyxl?

I currently have a simple list containing integers: amounts = [5, 10, 15] . 我目前有一个简单的列表,其中包含整数: amounts = [5, 10, 15] I would like to write these values into Excel cells, without having to type out statements for each element. 我想将这些值写入Excel单元格,而不必为每个元素键入语句。 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"] . 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. 如何使用cellsamounts一起进行迭代,以便可以将amounts[0]分配给A2 ,将amounts[1]分配给B2 ,依此类推。 This list is bigger in reality, just made it smaller for question's sake. 实际上,这个列表更大,只是出于问题的考虑而使其变小了。

You can set value into cell using method cell 您可以使用方法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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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