原始表格如下:
引入的模块如下:
pip install xlrd
pip install xlwt
运行结果:
打开表格检查:
源码如下:

"""python根据某一列内容拆分成多个excel""" import xlrd #对xls等excel文件的读取 import xlwt #对xls等excel文件的写入 workbook = xlrd.open_workbook(r"G:/博客园学习笔记(python)/python操作Excel/model.xlsx") #打开excel sheet = workbook.sheet_by_index(0)# 通过索引获取xls文件第0个sheet # 读取列,从0到第4列 从0到第n列 rows = [sheet.row_values(row,0,4) for row in range(sheet.nrows)] good_lists = {} # 根据第r[n]列数据进行分割 for r in rows: #因为我们是根据商品名称来切分,商品名在第三列。所以这里是r[2] if r[2] not in good_lists: good_lists[r[2]] = [] good_lists[r[2]].append(r) for (good, lst) in good_lists.items(): #这里的good存的是商品 wb = xlwt.Workbook() #新建sheet ws = wb.add_sheet(good) #这里先写入表头 ws.write(0,0,'包号') ws.write(0,1,'数量') ws.write(0,2,'名称') ws.write(0,3,'序号') row_idx = 1 for new_r in lst: #逐行写入 col_idx = 0 for v in new_r: ws.write(row_idx,col_idx,v) col_idx = col_idx + 1 row_idx = row_idx+1 #保存的文件名为商品,好分辨切分出来的excel属于哪和商品 wb.save('G:/博客园学习笔记(python)/python操作Excel/goods/'+good+'.xlsx')