我正在尝试制作一个将狼蛛物种添加到我的excel文档的应用程序。我使用openpyxl来做这件事,当我将第二个名字添加到B列时,它会将这个名字添加2次,而不是1次。
import openpyxl
import random
import time
wb = openpyxl.load_workbook("sample.xlsx")
ws = wb.active
def InsertGenus (genus):
for cellA in ws["A"]:
if cellA.value is None:
break
else:
print("Empty")
ws["A"+str(cellA.row + 1)] = genus
def InsertSpecies (species):
for cellB in ws["B"]:
if cellB.value is None:
break
else:
print("Empty")
ws["B"+str(cellB.row + 1)] = species
genus = input("Enter tarantula genus: ")
InsertGenus(genus)
species = input("Enter tarantula species: ")
InsertSpecies(species)
wb.save("sample.xlsx")
input("Press any key to exit...")发布于 2019-08-03 23:55:59
我将您的代码稍微重写为一个函数,并使用max_row+2用空单元格覆盖了基本情况。希望这对你有所帮助。
import openpyxl
import random
import time
wb = openpyxl.load_workbook("sample.xlsx")
ws = wb.active
def InsertTarantula (genus, species):
for row in range(1, ws.max_row+2):
if ws.cell(row=row, column=1).value == None and ws.cell(row=row, column=2).value == None:
#print(ws.cell(row=row, column=1).coordinate, ws.cell(row=row, column=2).coordinate)
ws.cell(row=row, column=1).value = genus
ws.cell(row=row, column=2).value = species
break
genus = input("Enter tarantula genus: ")
species = input("Enter tarantula species: ")
InsertTarantula(genus, species)
wb.save("sample.xlsx")
input("Press any key to exit...")https://stackoverflow.com/questions/57338463
复制相似问题