Openpyxl:将多列串联到每行一个单元格中(多行) [英] Openpyxl: Concatenation of several columns into one cell per row (Multi-row)
问题描述
此问题是后续措施: 我要做什么: 我想将每行从F列到M的单元格连接起来,并将连接后的值放入E列,如下所示.需要同时对所有行执行此操作.
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.
输入:
A B C D E F G H .. M
....... E1 90 2A .. 26
....... 0 80 F8 ..
输出:
A B C D E F G H .. M
....... E1902A..26
....... 080F8..
代码:
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()
我也将max列设置为N列(14),因为最长的代码一直持续到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!
推荐答案
正确的实现:
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()
这篇关于Openpyxl:将多列串联到每行一个单元格中(多行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!