所以我试图通过输入不同的单元格使我的代码打印出某个列。所以我设计了我的代码,让一个人输入五种不同类型的电影,然后openpyxl遍历excel文件,查找五部电影并打印出整行,但事情是它不断吐出错误,我不知道知道如何解决它
输出:
Traceback (most recent call last):
File "C:/Users/Shay/PycharmProjects/untitled/Assignment ITN.py", line 39, in <module>
listcreator(movieID)
File "C:/Users/Shay/PycharmProjects/untitled/Assignment ITN.py", line 28, in listcreator
if sheet.cell(row=r, column=c).value == movieOne:
AttributeError: 'Workbook' object has no attribute 'cell'
这是我的代码:
import csv
import openpyxl
from openpyxl import load_workbook
movieID = openpyxl.load_workbook(filename="C:/Users/Shay/Downloads/Movie IDs - Student Copy.xlsx")
movie_ID = movieID.active
movie_ID_List = []
movie_Ratings_list = []
mveavg = []
movieOne = input("Type first Movie\n")
movieTwo = input("Type in second movie\n")
movieThree = input("Type in third movie\n")
movieFour = input("Type in fourth movie\n")
movieFive = input("Type in fifth movie\n")
movieOneList = []
movieTwoList = []
movieThreeList = []
movieFourList = []
movieFiveList = []
def listcreator(sheet):
for r in range(1, 27278):
for c in range(1,2):
if sheet.cell(row=r, column=c).value == movieOne:
movieOneList.append(sheet.cell(row=r, column=0))
if sheet.cell(row=r, column=c).value == movieTwo:
movieTwoList.append(sheet.cell(row=r, column=0))
if sheet.cell(row=r, column=c).value == movieThree:
movieThreeList.append(sheet.cell(row=r, column=0))
if sheet.cell(row=r, column=c).value == movieFour:
movieFourList.append(sheet.cell(row=r, column=0))
if sheet.cell(row=r, column=c).value == movieFive:
movieFiveList.append(sheet.cell(row=r, column=0))
listcreator(movieID)
print(movieOneList)
print(movieTwoList)
print(movieThreeList)
print(movieFourList)
print(movieFiveList)
movieOneList - (movieOneList[0])
movieTwoList - (movieTwoList[0])
movieThreeList - (movieThreeList[0])
movieFourList - (movieFourList[0])
movieFiveList - (movieFiveList[0])
print(movieOneList)
print(movieTwoList)
print(movieThreeList)
print(movieFourList)
print(movieFiveList)
我还应该提一下,我是一个菜鸟编码器,所以如果这个问题看起来很基本但是很乐意帮助,我很抱歉
答案 0 :(得分:2)
你应该给你的变量更好的名字。
listcreator
函数接受一个Worksheet对象。但是当你调用它时,你传递的是movieID
,这是你在顶部加载的工作簿对象,而不是movie_ID
,这是该书中的活动工作表。
如果你把这些对象称为更合适的东西,你就可以更容易地看到你做错了什么。