如何使用Openpyxl将一行的数据合并到单个单元格中 [英] How to combine one row's data into a single cell using Openpyxl

查看:1110
本文介绍了如何使用Openpyxl将一行的数据合并到单个单元格中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将行中的3个单元格用-"分隔.

I have to combine 3 cells of a row separated by "-".

输入为:

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

我已经使用了以下内容,

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?

推荐答案

您正在尝试将row一起.join()无效.尝试尝试:

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

结果:

>>> 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')

这篇关于如何使用Openpyxl将一行的数据合并到单个单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆