问题
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-DMF
I have used the following,
for r1 in row:
strcell1 = '-'.join(map(str,row)) # converting to string list
cell1 = ''.join(strcell1) # joining the cells
list_value = [cell1]
ws.append(list_value) #writing on a different sheet of same workbook
But I am not getting the expected output, is there something that I am missing?
回答1:
You're trying to .join()
the row
s together which won't work. Try instead:
wb = openpyxl.load_workbook('your_workbook.xlsx')
ws1.get_sheet_by_name('Sheet1')
combined = []
for row in ws.rows:
combined.append('-'.join(r1.value for r1 in row))
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')
for val in combined:
ws2.append([val])
wb.save('your_workbook_modified.xlsx')
来源:https://stackoverflow.com/questions/42352862/how-to-combine-one-rows-data-into-a-single-cell-using-openpyxl