zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    Python 认识元组
    Python 认识字典
    Python 字符串中常见的一些方法续
    python 打印 A ~ Z
    Python3的print怎么让它不换行
    Python 中的 lstrip、rstrip、strip
    Python判断一个字符串是否包含指定字符串的方法
    Python 字符串中常见的一些方法
    Python 认识字符串
    苹果电脑MacbookPro双开微信!
  • 原文地址:https://www.cnblogs.com/angelyan/p/12581058.html
Copyright © 2011-2022 走看看