pandas拆分指定数量的excel

一、代码

import os
import pandas as pd

class PathError(BaseException):
    def __init__(self, error):
        self.error = error

class ReadError(BaseException):
    def __init__(self, error):
        self.error = error

class WriteError(BaseException):
    def __init__(self, error):
        self.error = error

class ExcelSplit():
    def __init__(self):
        pass

    def read(self, path):
        df = pd.read_excel(path)
        return df

    def split(self, path, dir, excel_name,amount):
        '''
        :param path: 被拆分excel
        :param dir: 拆分存放文件夹
        :param excel_name: 拆分文件名
        :param amount: 拆分数量
        :return:
        '''
        if not os.path.exists(path):
            raise PathError("文件地址不存在")
        if not isinstance(amount, int):
            return {"error": "amount为int"}
        if not os.path.exists(dir):
            os.mkdir(dir)
        try:
            df = self.read(path)
        except Exception as e:
            raise ReadError("文件读取失败")

        if len(df) > amount:
            for i in range(amount):
                if i == amount-1:
                    i_df = df[i * (len(df) // amount):len(df)]
                else:
                    i_df = df[i * (len(df) // amount):len(df) // amount * (i + 1)]
                i_df.to_excel(dir + "/" + "{}{}.xlsx".format(excel_name,i), index=False)
            return {"msg":"成功拆成{}份".format(amount)}
        return {"error":"原表拆分数量不够"}

if __name__ == '__main__':
    path=r"********.xlsx"
    dir=r"*******文件夹"
    excel_name="文件名"
    amount=5
    es=ExcelSplit()
    es.split(path,dir,excel_name,amount)

 

猜你喜欢

转载自www.cnblogs.com/angelyan/p/12581058.html