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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM