'tuple' 对象没有属性 'value' openpyxl

'tuple' object has no attribute 'value' openpyxl

我制作了一个脚本,将范围从一个 excel sheet 复制到另一个范围,但是当我 运行 它时,我 运行 出现以下错误。

Traceback (most recent call last):
  File "d:\Python\LCR_skema_opdater2203-test\Skema\Moder\LCR_opdater_skema.py", line 31, in <module>
    cell2.value = cell1.value
AttributeError: 'tuple' object has no attribute 'value'

这是我写的脚本:

import openpyxl
import os

#Current path
path = os.path.dirname(os.path.abspath(__file__))

#Beregningsmodul navn
Beregningsmodul_moder_navn = "Beregning COREP LCR - MODER - 202202.xlsx"

#workbook_beregn path
beregn_path = path + "\" + Beregningsmodul_moder_navn
workbook_beregn = openpyxl.load_workbook(beregn_path)

#Skema 72 navn
skema_72_navn ="C_72_00_a.xlsx"
#skema path
skema_72_path = path + "\" + skema_72_navn
workbook_skema_72 = openpyxl.load_workbook(skema_72_path)

#Kopier til
wb_72C = workbook_beregn["72C"]['E8':'G54']

#kopier fra
C_72_00_a = workbook_skema_72["C_72_00_a"]['D9':'F55']

#Pair the rows
for row1,row2 in zip(C_72_00_a, workbook_beregn):
    #within the row pair, pair the cells
    for cell1, cell2 in zip(row1,row2):
        #assign the value of cell 1 to the destination cell 2 for each row
        cell2.value = cell1.value
#save document
workbook_beregn.save('destination.xlsx')
print("Finished")

希望你能给我指出正确的方向。

#更新:

我找到了一个解决方案并最终定义了一个函数以便将来更容易复制:

#Copy from
wb_72C = workbook_beregn['72C']['E8':'G54']

#Copy to
C_72_00_a = workbook_skema_72['C_72_00_a']['D9':'F55']

#Define function
def workbook_copy(copy_from,copy_to):
    #Pair the rows
    for row1,row2 in zip(copy_from, copy_to):
        #within the row pair, pair the cells
        for cell1, cell2 in zip(row1,row2):
            #assign the value of cell 1 to the destination cell 2 for each row
            cell2.value = cell1.value

workbook_copy(C_72_00_a, wb_72C)

当迭代为运行时,return对象是一个元组(给定行的单元格中所有值的组合) 例如('A', '123', 'CD' , 125) 将是具有四列的行的结果

要将值从源单元格复制到目标单元格,您需要遍历单元格的坐标(行地址和列地址)

当您遍历行时,代码只理解行而不是行中的每个单元格。 因此错误,“AttributeError:'tuple' object has no attribute 'value'”

希望对您有所帮助

我发现问题是我正在遍历工作簿而不是我创建的元组。

wb_72C = workbook_beregn['72C']['E8':'G54']
C_72_00_a = workbook_skema_72['C_72_00_a']['D9':'F55']
#Pair the rows
for row1,row2 in zip(C_72_00_a, wb_72C):
    #within the row pair, pair the cells
    for cell1, cell2 in zip(row1,row2):
        #assign the value of cell 1 to the destination cell 2 for each row
        cell2.value = cell1.value

所以我更改了这一行:

for row1,row2 in zip(C_72_00_a, workbook_beregn):

到这一行:

for row1,row2 in zip(C_72_00_a, wb_72C):

我希望这个人在未来。