openpyxl 在 Excel 中写入多行
openpyxl write multiple rows in Excel
我正在尝试将多行写入 Excel。 "Containers" 的 index/len 为 10。虽然我遍历它,但当我 运行 脚本时我只得到一行。
谁能帮我解决这个问题?
# 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")
你的问题是你在同一行用 e=sheet.cell(row=start_row,column=1+i)
写出了所有内容。
因为所有内容都包含在循环 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
我考虑的另一条路线是将 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()
我正在尝试将多行写入 Excel。 "Containers" 的 index/len 为 10。虽然我遍历它,但当我 运行 脚本时我只得到一行。
谁能帮我解决这个问题?
# 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")
你的问题是你在同一行用 e=sheet.cell(row=start_row,column=1+i)
写出了所有内容。
因为所有内容都包含在循环 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
我考虑的另一条路线是将 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()