Skip to content Skip to sidebar Skip to footer

How To Combine One Row's Data Into A Single Cell Using Openpyxl

I have to combine 3 cells of a row separated by '-'. Input is: A1 A9 AMF A2 B9 BMF A1 A9 AMF (Same as 1st row) A4 D9 DMF Expected Output is: A1-A9-AMF A2-B9-BMF A4-D9-DM

Solution 1:

You're trying to .join() the rows together which won't work. Try instead:

wb = openpyxl.load_workbook('your_workbook.xlsx')
ws1.get_sheet_by_name('Sheet1')
combined = []
forrowin ws.rows:
    combined.append('-'.join(r1.value for r1 inrow))

Result:

>>> print(combined)
[u'A1-A9-AMF', u'A2-B9-BMF', u'A1-A9-AMF', u'A4-D9-DMF']

Write result to other sheet:

ws2 = wb.create_sheet('Sheet2')
forvalin combined:
    ws2.append([val])
wb.save('your_workbook_modified.xlsx')

Post a Comment for "How To Combine One Row's Data Into A Single Cell Using Openpyxl"