Python 2.7 如何使用.cell()解决连接问题?行=行工作,列=列给出错误
我在excel表格中循环,寻找一个特定的名称。找到后,我打印单元格的位置和值 我希望找到相邻单元格的位置和值,但是我无法通过添加2使.cell()工作,这表示我希望单元格2列位于同一行中 行=行有效,但列=列给出错误,列+2给出错误。也许这是因为我在前面的代码中将列列列列为“ABCDEFGHIJ”?(完整代码见下文) 完整代码:Python 2.7 如何使用.cell()解决连接问题?行=行工作,列=列给出错误,python-2.7,openpyxl,Python 2.7,Openpyxl,我在excel表格中循环,寻找一个特定的名称。找到后,我打印单元格的位置和值 我希望找到相邻单元格的位置和值,但是我无法通过添加2使.cell()工作,这表示我希望单元格2列位于同一行中 行=行有效,但列=列给出错误,列+2给出错误。也许这是因为我在前面的代码中将列列列列为“ABCDEFGHIJ”?(完整代码见下文) 完整代码: file = openpyxl.load_workbook('test6.xlsx', read_only = True) allSheetNames = file.s
file = openpyxl.load_workbook('test6.xlsx', read_only = True)
allSheetNames = file.sheetnames
#print("All sheet names {}" .format(file.sheetnames))
for sheet in allSheetNames:
print('Current sheet name is {}'.format(sheet))
currentSheet = file[sheet]
for row in range(1, currentSheet.max_row + 1):
#print row
for column in 'ABCDEFGHIJ':
cell_name = '{}{}'.format(column,row)
if currentSheet[cell_name].value == 'sign_name':
print 'Cell position {} has value {}'.format(cell_name, currentSheet[cell_name].value)
print 'Cell position TEST {}'.format(currentSheet.cell(row=row, column=column +2))
我得到这个输出:
Current sheet name is Sheet1
Current sheet name is Sheet2
Cell position D5 has value sign_name
以及:
如果我尝试“column=column”作为“column=column+2”,则会得到相同的错误
为什么行=行有效,而列=列无效?如何在生成的D5单元格右侧找到单元格的单元格名称
row=row
有效而column=column
无效,是因为column
值是一个字符串(字母从a到J),而单元格的column
参数需要int
(a是1,B是2,Z是26,等等)
sheet.iter_rows()
,它不提供任何参数,将提供一个表中使用的所有行的生成器。因此,您可以使用
用于currentSheet.iter_rows()中的行:
对于行中的单元格:
因为每个行
都是该行中单元格的生成器
然后在这个新的嵌套for循环中,您可以使用cell.column
(D将给出4)获得当前列索引,右边的单元格(增量为一列)将是currentSheet.cell(行=行,列=单元格.column+1)
请注意两个单元格
之间的差异:currentSheet.cell()
是对特定单元格的请求,而单元格。column+1
是当前单元格的列索引增加1
相关OpenPyXl文档:
或者更简单的:
用于当前工作表中的行…
Current sheet name is Sheet1
Current sheet name is Sheet2
Cell position D5 has value sign_name
TypeError: cannot concatenate 'str' and 'int' objects