问题
This question is a follow up to: Openpyxl: TypeError - Concatenation of several columns into one cell per row
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. This needs to be done for all rows at the same time.
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..
Code:
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[:]
pass
sheet[f'E{row_value}'].value= ''.join(values)
concat_f_to_m()
Also I have set the max column to column N (14) as the longest code goes until column M and I want to stop the loop once there is no entry found in order to go out and join the list's items. I cannot overcome the issue that despite a print of the values list shows only the row's items, it does not write it down into the cell. Could you give me a hint how to concatenate through all rows by joining the values list at the certain row? Thank you!
回答1:
Correct implementation:
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))
sheet[f'E{row_value}'].value= ''.join(values)
else:
del values[:]
break
concat_f_to_m()
来源:https://stackoverflow.com/questions/60143273/openpyxl-concatenation-of-several-columns-into-one-cell-per-row-multi-row