我必须组合一行的3个单元格,用" - "。
分隔输入为:
A1 A9 AMF
A2 B9 BMF
A1 A9 AMF (Same as 1st row)
A4 D9 DMF
预期输出为:
A1-A9-AMF
A2-B9-BMF
A4-D9-DMF
我使用了以下内容,
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
但是我没有得到预期的输出,是否有我遗漏的东西?
答案 0 :(得分:0)
您正在尝试false
.join()
一起工作的row
。请尝试改为:
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))
结果:
>>> print(combined)
[u'A1-A9-AMF', u'A2-B9-BMF', u'A1-A9-AMF', u'A4-D9-DMF']
将结果写入其他工作表:
ws2 = wb.create_sheet('Sheet2')
for val in combined:
ws2.append([val])
wb.save('your_workbook_modified.xlsx')