How to combine one row's data into a single cell using Openpyxl

我与影子孤独终老i 提交于 2019-12-12 01:46:42

问题


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 rows 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!