openpyxl處理excel數據 & python中的時間格式


python中的時間格式

%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12)
%M 分鍾數(00=59)
%S 秒(00-59)

openpyxl處理excel數據

填充顏色和漸變色

#from openpyxl.styles importPatternFill

fill = PatternFill(fill_type = None,start_color='FFFFFF',end_color='000000')

ws.['B1'].fill = fill

實例

import pandas as pd
import datetime
import time
import openpyxl
import openpyxl.styles
from openpyxl.styles import PatternFill

def getpara(month):
    if month > 4:
        return 1
    elif month > 7:
        return 2
    elif month > 9:
        return 3
    else:
        return 4

def getpara1(month):
    return 4 - getpara(month)

#先定義起始和結束日期當年對應的報告期數

def parseOneCol(item):
    ret = []#定義一個列表

    startTime = str(item[2])#item[2]列表索引,轉換成str格式
    d = datetime.datetime.strptime(startTime, '%Y%m%d')
    endTime = str(item[3])
#datetime.datetime.strptime(字符串,時間格式)

    tmp = d.year - 1998
    if tmp < 0:
        start = 4
    else:
        start = tmp + 5
#如果起始年比1998小則從1998這一列開始,如果比1998大則從起始年后一年開始
    if tmp >= 0:
        if item[tmp + 4] < getpara(d.month):
            ret.append(tmp + 4)
#如果起始年>=1998,其對應的值小於理應的值,則在ret中插入該對象
    d2 = datetime.datetime.strptime(endTime, '%Y%m%d.0')
    end = d2.year - 1998 if d2.year < 2021 else 2021 -1998
    if item[end+4] < getpara1(d2.month):
        ret.append(end+4)

#如果在結束年的位置,其對應的值小於理應的值,則在ret中插入該對象
    for i in range(start, end):
        if item[i] < 4:
            ret.append(i)
#如果在起始年和結束年之間的數值<4,則加在ret中插入該對象
    return ret


path = r'C:\report_year(annip_asset_alloc).xlsx'
df = pd.read_excel(path, engine=None)#讀取excel數據
df['maturity_date']=df['maturity_date'].fillna(value=20210907)
#填充結束年為空的為當前日期

data = df.values#返回的是不帶標簽的數據集
ret = []
for i, item in enumerate(data):#枚舉data
    t = parseOneCol(item)
    if t:
        ret.append((i + 2, t))
#循環parseOneCol函數

path1 = r'C:\test.xlsx'
wb = openpyxl.load_workbook(path1)
#load_workbook()函數接受文件名,返回一個 workbook 數據類型的值
sheet = wb["Sheet1"]
#獲取sheet頁
fille = PatternFill("solid", fgColor="FFBB02")#填充顏色


for (i, t) in ret:
    for j in t:
        sheet.cell(i, j + 1).fill = fille
#sheet.cell()讀取單個數據表格信息
wb.save("test.xlsx")
wb.close()


免責聲明!

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



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