Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

python - Openpyxl: TypeError - Concatenation of several columns into one cell per row

I am new to openpyxl and cannot figure out what the reason for my error is. I hope you can see the problem and show me what to change!

What I want to do: I want to concatenate the cells from columns F to M per row and put the concatenated value into column E like below. (The rows do not always fill up from column F to column M, since per row are different kind of signals. But I have not put an if clause for this yet. This is just an information about the structure.)

Input:

A B C D E F   G   H  .. M
.......   E1  90  2A .. 26
.......   0   80  F8 .. 

Output:

A B C D E         F   G   H  .. M
....... E1902A..26
....... 080F8..

What I did so far (Code):

theFile = openpyxl.load_workbook('T013.xlsx')
allSheetNames = theFile.sheetnames 
print("All sheet names {} " .format(theFile.sheetnames)) 
sheet = theFile.active

#loop to concatenate
for i,row in enumerate(sheet.rows,1):
        for column in range(6,13): #column F-M
            sRow=str(i)  
            Ecell = sheet['E' + sRow]
            ref = sheet["F:M"] #range of cells 
            for cell in range(ref):
                values = str(cell.value)  #collect data
            Ecell.value = ''.join(values) # write values

Which kind of error I get (complete Traceback):

C:Users..DesktopPractical PartCAN Python>python ConcatenateHEX.py
All sheet names ['T013']
Traceback (most recent call last):
  File "ConcatenateBIN.py", line 38, in <module>
    for cell in range(ref):
TypeError: 'tuple' object cannot be interpreted as an integer

I already tried to change the 'ref' variable but the error is always the same! Could you please support me? Thank you very much!

EDIT (2/10/2020): Further, I want to use the function for all rows which are too many to write down. Therefore I came up with this change:

def concat_f_to_m():
for row_value in range(1, sheet.max_row+1):
    values=[]
    del values[:]   
    for row in sheet.iter_rows(min_col=6, max_col=14, min_row=row_value, max_row=row_value):
        for cell in row:
            if cell.value != None:
                values.append(str(cell.value))
            else:
                del values[:] 
                break
                #print(values)
    sheet[f'E{row_value}'].value= ''.join(values)

concat_f_to_m()

I cannot overcome the issue that all the values from row 1 to row xyz are printed in the row_value cell (e.g. row_value=13, all values from row 1 to 13 are concatenated in cell E13). I therefore wanted to iterate over row_value in order to go through all rows but somehow that does not work. Could you give me a hint how to concatenate through all rows by joining the values list at the certain row? Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using openpyxl, I created a little function that will do what you want for a line at a time:

import openpyxl

theFile = openpyxl.load_workbook('T013.xlsx')
allSheetNames = theFile.sheetnames 
print("All sheet names: {}" .format(theFile.sheetnames)) 
sheet = theFile.active


def concat_f_to_m(row_value):
    values=[]
    del values[:]
    for row in sheet.iter_rows(min_col=6, max_col=13, min_row=row_value, max_row=row_value):
        for cell in row:
            if cell.value == None:
                pass
            else:
                values.append(str(cell.value))
    sheet[f'E{row_value}'].value= ''.join(values)


concat_f_to_m(1)
concat_f_to_m(2)
theFile.save('T013.xlsx')

Output:

Excel Output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...