pandas to_excel 添加顏色


import pandas as pd
import numpy as np

columns = [['A', 'A', 'B', 'B', 'C'], ['a', 'b', 'c', 'd', 'e']]
# 創建形狀為(10,5) 的DataFrame 並設置二級標題 demo_df = pd.DataFrame(np.arange(50).reshape(10, 5), columns=columns) print(demo_df) def style_color(df, colors): """ :param df: pd.DataFrame :param colors: 字典 內容是 {標題:顏色} :return: """ return df.style.apply(style_apply, colors=colors) def style_apply(series, colors, back_ground=''): """ :param series: 傳過來的數據是DataFramt中的一列 類型為pd.Series :param colors: 內容是字典 其中key 為標題名 value 為顏色 :param back_ground: 北京顏色 :return: """ series_name = series.name[0] a = list() # 為了給每一個單元格上色 for col in series:
# 其中 col 為pd.DataFrame 中的 一個小單元格 大家可以根據不同需求為單元格設置不同的顏色 # 獲取什么一級標題獲取什么顏色 if series_name in colors: for title_name in colors: if title_name == series_name: back_ground = 'background-color: ' + colors[title_name] # '; border-left-color: #080808' a.append(back_ground) return a style_df = style_color(demo_df, {"A": '#1C1C1C', "B": '#00EEEE', "C": '#1A1A1A'}) with pd.ExcelWriter('df_style.xlsx', engine='openpyxl') as writer:
#注意: 二級標題的to_excel index 不能為False style_df.to_excel(writer, sheet_name='sheet_name')

 以上就是pandas.DataFrame 二級標題to_excel()  添加顏色的demo  大家可以自行根據不同需求修改  

主要注意

style_apply 方法中的內容  里面是真正設置顏色的地方


免責聲明!

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



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