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)
  • 相关阅读:
    Leetcode.11 Container with Most Water
    Leetcode.19 Remove Nth Node From End of List
    Leetcode23. Merge K sorted List
    leetcode287. Find the duplicate Number
    LeetCode234. Palindrome Linked List
    leetcode.142 LinkedList Cycle II
    UINavigationController
    UITableView的性能优化1
    iOS触摸事件
    UITableView的性能优化
  • 原文地址:https://www.cnblogs.com/angelyan/p/12581058.html
Copyright © 2011-2022 走看看