python 把EXCEL 數據 從日期按年份分組篩選到新sheet

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

import os
import openpyxl
import datetime
import time

year_list = [2013, 2014, 2015, 2016, 2017, 2018]
file_path = r"F:/test"
file_name = "數據按年份篩查到新的工作薄.xlsx"
file_result = os.path.join(file_path, file_name)


def excel():
    """
    """
    wb = openpyxl.load_workbook(file_result)  #  首先獲取excel文件生成對象wb 使用openpyxl.load_workbook 方法
    sh = wb.active  #  使用wb中的active方法獲取當前工作薄:btc 生成新的對象sh
    index = 0  #  設置一個數字變量之後會用到
    for i in range(len(year_list)): # 循環6次,6次來源於year_list列表長度
        count = 2 # 定義一個數字變量 後面會用到
        sh1 = wb.create_sheet(str(year_list[index])) # 使用使用wb.create 方法創建工作薄名稱。名稱爲列表中的值,index是上面定義的數字變量
        
        for rows in sh.rows:   # 循環btc工作薄表中的內容
            if rows[1].coordinate != "B1" and datetime.datetime.strptime(rows[1].value, '%Y/%m/%d %H:%M:%S').year == year_list[index]:
              # 把日期和金額去除從第二行開始循環, 使用datetime模塊將獲取的value1的時間字符串解析爲時間元組。 最後取年值進行匹配
                # print(rows[0].value, rows[1].value)
                sh1["A1"] = "編號"
                sh1["B1"] = "日期"
                sh1["C1"] = "姓名"
                sh1["D1"] = "電話"
                sh1["E1"] = "住址"
                sh1["A" + str(count)] = rows[0].value # A + str(count) 第二行開始 寫入
                sh1["B" + str(count)] = rows[1].value
                sh1["C" + str(count)] = rows[2].value
                sh1["D" + str(count)] = rows[3].value
                sh1["E" + str(count)] = rows[4].value

                # print("in sh:", sh1["A" + str(count)].value, sh1["B" + str(count)].value)
                print(f"正在分析{year_list[index]}年數據.....")
                count += 1 # 沒完成一次循環 count + 1
        index += 1 # 同時index + 1
    wb.save("F:/test/數據按年份篩查到新的工作薄-已處理.xlsx") # 當函數全部執行完成後,使用wb.save 保存即可。
#print(wb)
if __name__ == "__main__":
   start_time = time.time()
   excel()
   print(f"分析完成,用時時間爲{time.time() - start_time}秒")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章