利用python将excel表拆分为多页sheet的多张excel

任务目标:根据汇总表数据,按照各单位区域划分,拆成各区域模块下的多个sheet镇街excel表

(说明:所有数据均做清洗或者作假,防止追究责任)

任务图片:利用python将excel表拆分为多页sheet的多张excel

效果图片:利用python将excel表拆分为多页sheet的多张excel

附上代码

#!/usr/bin/python
# -*- coding:utf-8 -*-

import pandas as pd
import os


# 一、拆分客户汇总表
path = r'C:\**\客户汇总表0321.xlsx'
data = pd.read_excel(path, sheet_name=u'汇总表', skiprows=1)
rows = data.shape[0]
danwei_list = list()

if __name__ == '__main__':
    for i in range(rows):
        temp = data[u'单位'][i]
        if temp not in danwei_list:
            danwei_list.append(temp)

if __name__ == '__main__':
    for danwei in danwei_list:
        new_df = pd.DataFrame()
        for i in range(0, rows):
            if data[u'单位'][i] == danwei:
                new_df = pd.concat([new_df, data.iloc[[i], :]], axis=0, ignore_index=True)
        new_df.to_excel(str(danwei)+'.xls', sheet_name=u'单位汇总', index=False)

# 二、拆分各单位报表,按镇区分为多个sheet表
xlsx_names = [x for x in os.listdir() if x.endswith('.xls')]
for xlsx_name in xlsx_names:
    ndata = pd.read_excel(xlsx_name)
    nrows = ndata.shape[0]

    zhenqu_list = []
    for i in range(nrows):
        temp = ndata[u'镇区'][i]
        if temp not in zhenqu_list:
            zhenqu_list.append(temp)

    n = len(zhenqu_list)
    writer = pd.ExcelWriter(xlsx_name)
    for zhenqu in range(n):
        df = pd.DataFrame()
        for i in range(0, nrows):
            if ndata[u'镇区'][i] == zhenqu_list[zhenqu]:
                df = pd.concat([df, ndata.iloc[[i], :]], axis=0, ignore_index=True)
        df.to_excel(writer, sheet_name=str(zhenqu_list[zhenqu]), encoding="utf-8", index=False)
    writer.save()
    writer.close()    

参考链接:利用Python将一张Excel文件的sheet拆分成多个sheets