[英]openpyxl write multiple rows in Excel
I am trying to write multiple rows to Excel. 我试图将多个行写入Excel。 "Containers" has an index/len of 10. Although I loop through it, I only get one row when I run the script. “容器”的索引/长度为10。尽管我循环浏览它,但运行脚本时只得到一行。
Can anyone help me with this? 谁能帮我这个?
# define first empty row
start_row = sheet.max_row + 1
#write to excel
for container in containers:
#Company name
company_container = container.div.h2
company = company_container.text.strip()
#City
city = container.div.a["title"]
#URL
url = container.div.div.a["href"]
#Title
title_container = container.findAll("div", {"class":"info"})
title = title_container[0].img["alt"]
#Description
description = title_container[0].p.text
#Programming language
hardskill = "Java"
#Vervolgactie (Teamleader)
vervolgactie = "Nieuw"
companyinfo = [company, city, url, title, description, hardskill, vervolgactie]
for i in range(0,len(companyinfo)):
e=sheet.cell(row=start_row,column=1+i)
e.value=companyinfo[i]
wb.save("vacatures.xlsx")
Your problem is that you're writing everything out with e=sheet.cell(row=start_row,column=1+i)
on the same row. 您的问题是您在同一行上用e=sheet.cell(row=start_row,column=1+i)
写出所有内容。
since everything in enclosed in the loop for container in containers
, i'd just increment start_row
after the sub loop. 由于所有内容都包含在for container in containers
循环for container in containers
,因此我只会在子循环之后增加start_row
。
for i in range(0,len(companyinfo)):
e=sheet.cell(row=start_row,column=1+i)
e.value=companyinfo[i]
start_row +=1 #not part of the above loop but part of the overarching loop
Another route i'd consider is to rename start_row
to just row (this is more semantically clear) and have row
defined in the loop 我考虑的另一种方法是将start_row
重命名为仅一行(这在语义上更清晰),并在循环中定义row
#start_row = sheet.max_row + 1
#write to excel
for container in containers:
#row for this data to go on.
row = sheet.max_row + 1
#Company name
company_container = container.div.h2
company = company_container.text.strip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.