我的 Excel 工作表 A 列中有 ID 号,但有时它们是相同的。在本例中,我希望程序获取 I 列中的文本并将其连接起来。第 I 列可以有 1 到 n 行具有相同的 ID
示例:
从这里开始
A 栏 | 第一栏 |
---|---|
197 | 这是示例 1 |
198 | 这是 |
198 | 示例 2 |
199 | 这是示例 3 |
到这里
A 栏 | 第一栏 |
---|---|
197 | 这是示例 1 |
198 | 这是示例 2 |
199 | 这是示例 3 |
A 列保留两行还是合并为一行并不重要,重要的是 I 列合并。
我尝试迭代每一行,检查前后行是否相同。但我遇到的困难是将新加入的列表放在另一列中。现在,我得到的 Excel 列表看起来与源代码没有什么不同。
mylist = []
for cell in sheet['A']:
mylist.append(cell.value)
textlist = []
for cell in sheet['I']:
textlist.append(str(cell.value))
mergecount=0
startcell=1
sheet.insert_cols(10)
for row in range(1, len(mylist)):
print(row, mylist[row-1], mylist[row])
if mylist[row-1] == mylist[row]:
mergecount += 1
else:
print(row, mylist[row-1], mylist[row], startcell, mergecount)
if mergecount > 0:
for text in textlist:
newcells = ' '.join(text)
cell.value = newcells
mergecount = 0
startcell = row+1
if mergecount > 0:
for text in textlist:
newcells = ' '.join(text)
cell.value = newcells
workbook.save(file)
我重写了一些代码,试图模仿你的风格和变量名称,以使其更容易理解。
对于第一部分,我们可以使用与您所做的相同的列表数据捕获:
import openpyxl
from openpyxl import load_workbook
file = "Book1.xlsx"
workbook = load_workbook(file)
sheet = workbook.active
mylist = []
for cell in sheet['A']:
mylist.append(cell.value)
textlist = []
for cell in sheet['I']:
textlist.append(str(cell.value))
之后,我们可以创建 2 个新列表来保存新 ID 和新文本,我会从 0 开始迭代,而不是从“1”开始迭代:
mylist_new = []
textlist_new = []
for row in range(0, len(mylist)):
if row == 0:
newtext = textlist[row]
else:
if mylist[row-1] == mylist[row]:
# The operator '+' is going to work to concatenate strings:
newtext = newtext + ' ' + textlist[row]
else:
mylist_new.append(mylist[row-1])
textlist_new.append(newtext)
newtext = textlist[row]
# I need these last 2 lines to save the last values of both: IDs and text:
mylist_new.append(mylist[-1])
textlist_new.append(newtext)
最后,您可以将新列表中的数据保存在 2 个不同的列中(在本示例中,我将在 J 列(第 10 列)和 K 列(第 11 列)上使用相同的工作表:
for row in range(0, len(mylist_new)):
sheet.cell(row=row+1, column=10).value = mylist_new[row]
for row in range(0, len(textlist_new)):
sheet.cell(row=row+1, column=11).value = textlist_new[row]
workbook.save(file)
希望能帮到你。