場(chǎng)景概述
將merge_res.xlsx文件中A列數(shù)據(jù)中相同班級(jí)合并單元格
準(zhǔn)備工作
將A列數(shù)據(jù)排序保存
工具準(zhǔn)備
openpyxl模塊
代碼實(shí)現(xiàn)
from openpyxl import load_workbook
# 需要處理的文件
file = r'C:/Users/Administrator/Desktop/test/merge_res.xlsx'
wb = load_workbook(file)
# 數(shù)據(jù)存放的工作表'Sheet1'
ws = wb['Sheet1']
# 獲取第一列數(shù)據(jù)
type_list = []
i = 2
while True:
r = ws.cell(i, 1).value
if r:
type_list.append(r)
else:
break
i += 1
# 判斷合并單元格的始末位置
start = 0
end = 0
flag = type_list[0]
for i in range(len(type_list)):
if type_list[i] != flag:
flag = type_list[i]
end = i - 1
if end >= start:
ws.merge_cells("A" + str(start + 2) + ":A" + str(end + 2))
start = end + 1
if i == len(type_list) - 1:
end = i
ws.merge_cells("A" + str(start + 2) + ":A" + str(end + 2))
wb.save(file)
執(zhí)行代碼川抡,返回文件打開merge_res.xlsx溢吻,需求完成刻获!
下節(jié)县踢,我們將介紹如何批量實(shí)現(xiàn)Excel單元格中叁鉴,按相同條件進(jìn)行組合C嘣邸1蛤尽空幻!