首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python向excel文档添加了太多行

Python向excel文档添加了太多行
EN

Stack Overflow用户
提问于 2019-08-03 20:50:03
回答 1查看 40关注 0票数 0

我正在尝试制作一个将狼蛛物种添加到我的excel文档的应用程序。我使用openpyxl来做这件事,当我将第二个名字添加到B列时,它会将这个名字添加2次,而不是1次。

代码语言:javascript
复制
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...")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-03 23:55:59

我将您的代码稍微重写为一个函数,并使用max_row+2用空单元格覆盖了基本情况。希望这对你有所帮助。

代码语言:javascript
复制
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...")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57338463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档