如何解决连接问题 with.cell()?行 = 行工作,列 = 列给出错误

how to solve concatenate issue with.cell()? row = row work, column = column gives error

我正在遍历 excel sheet,寻找特定名称。找到后,我打印单元格的位置和值。

我想找到相邻单元格的位置和值,但是我无法通过加 2 来使 .cell() 工作,这表明我希望单元格在同一行中相距 2 列。

row= row 有效,但 column= column 出错,column + 2 出错。也许这是因为我在代码的前面将列列为 'ABCDEFGHIJ'? (完整代码见下文)

print 'Cell position {} has value {}'.format(cell_name, currentSheet[cell_name].value)
print 'Cell position next door TEST {}'.format(currentSheet.cell(row=row, column=column +2))

完整代码:

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

和:

TypeError: cannot concatenate 'str' and 'int' objects 

如果我尝试使用“column = column”作为“column = column +2”,我会得到同样的错误。

为什么 row=row 有效,而 column=column 无效?以及如何找到我生成的 D5 单元格右侧单元格的单元格名称?

  1. row=row 有效而 column=column 无效的原因是 你的 column 值是一个字符串 (从 A 到 J 的字母),而单元格的 column 参数 期待 int (A 为 1,B 为 2,Z 为 26等)

  2. 为了更有效地遍历单元格并找到邻居,我将进行一些更改。首先,OpenPyXl 提供 sheet.iter_rows(),它不提供任何参数,将提供 sheet 中使用的所有行的生成器。所以你可以用

    迭代

for row in currentSheet.iter_rows():

for cell in row:

因为每个 row 都是该行中单元格的生成器。

然后在这个新的嵌套 for 循环中,您可以使用 cell.column 获取当前列索引(D 将给出 4),右侧的单元格(增加一列)将是 currentSheet.cell(row=row, column=cell.column+1)

注意两个 cell 之间的区别:currentSheet.cell() 是对特定单元格的请求,而 cell.column+1current[ 的列索引=50=] 单元格递增 1.

相关 OpenPyXl 文档:

https://openpyxl.readthedocs.io/en/stable/api/openpyxl.cell.cell.html https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html