Pandas之StyleFrame如何設置表格樣式
對于Excel樣式設置庫——StyleFrame
也做簡單介紹:
1、安裝
pip install StyleFrame
2、基礎數(shù)據(jù)暫時都用data(模擬數(shù)據(jù))做測試
from StyleFrame import StyleFrame, Styler
for sheet in data.keys():
sf = StyleFrame(data[sheet]) #實例化數(shù)據(jù)對象
sf不同于DataFrame表的df,是不可以預覽的。
3、Styler——樣式設置對象
詳情可前去官網(wǎng)查看: StyleFrame官網(wǎng)
Styler(bg_color=None, bold=False, font=utils.fonts.arial, font_size=12, font_color=None, number_format=utils.number_formats.general, protection=False, underline=None, border_type=utils.borders.thin, horizontal_alignment=utils.horizontal_alignments.center, vertical_alignment=utils.vertical_alignments.center, wrap_text=True, shrink_to_fit=True, fill_pattern_type=utils.fill_pattern_types.solid, indent=0, comment_author=None, comment_text=None, text_rotation=0)
解釋:
| 參數(shù) | 說明 |
|---|---|
| bg_color | 單元格背景色 |
| bold | 字體加粗與否設置 |
| font | 字體類型 |
| font_size | 字體大小 |
| font_color | 字體顏色 |
| number_format | 數(shù)值格式 |
| protection | 保護表格不被修改 |
| underline | 下劃線設置 |
| border_type | 邊框線設置 |
| horizontal_alignment | 水平方向?qū)R設置 |
| vertical_alignment | 垂直方向?qū)R設置 |
| wrap_text | 是否自動換行 |
| shrink_to_fit | 是否根據(jù)字符長度縮小以適應單元格 |
| fill_pattern_type | 背景填充模式 |
| indent | 縮進距離 |
| comment_author | 批注作者 |
| comment_text | 批注內(nèi)容 |
a)在某一列上使用樣式時需要用到如下方法
apply_column_style(cols_to_style,styler_obj,style_header)
- 1、cols_to_style:要設置樣式的列名
- 2、styler_obj:樣式對象,即上面設置過的Styler
- 3、style_header:是否將表頭也設置樣式
實例:
sf.apply_column_style(cols_to_style=["列名",'列名1'],
styler_obj=Styler(number_format="0"),
style_header=True)
b)在行上使用
apply_style_by_indexes(indexes_to_style,styler_obj,cols_to_style)
- 1、indexes_to_style: 要設置樣式的行,sf[sf[‘col1’] = 20]表示設置col1列等于20的行
- 2、styler_obj: 樣式對象
- 3、cols_to_style: 要設置通過indexes_to_style選出那些行對應的哪些列
實例:
indexes_to_style=sf[sf['列名'] < '10'] # 列名列數(shù)值小于10的單元格
#sf.apply_style_by_indexes(indexes_to_style=sf[sf['列名'] < '10'],
cols_to_style=['列名'],styler_obj=Styler(font_color="#FF0000"))
c)字體大小:font_size\加粗:bold
sf.apply_column_style(cols_to_style=["col_2"],
styler_obj=Styler(font_size=12, bold=True),
style_header=True)
d)背景色:bg_colors
sf.apply_column_style(cols_to_style=["col_2"],
styler_obj=Styler(bg_color='red'),
style_header=True)
e)對齊方式:horizontal_alignment
general = 'general' #一般 left = 'left' #左對齊 center = 'center' #居中對齊 right = 'right' #右對齊 fill = 'fill' #填滿單元格對齊 justify = 'justify' #兩端對齊 center_continuous = 'centerContinuous' distributed = 'distributed' #分散對齊
實例:
sf.apply_column_style(cols_to_style=["col_3"],
styler_obj=Styler(horizontal_alignment="center"),
style_header=True)
f)垂直方向?qū)R:vertical_alignment
top = 'top' #靠上對齊 center = 'center' #靠中對齊 bottom = 'bottom' #靠下對齊 justify = 'justify' #兩端對齊 distributed = 'distributed' #分散對齊
實例:
sf.apply_column_style(cols_to_style=["col_3"],
styler_obj=Styler(vertical_alignment="center"),
style_header=True)
g)數(shù)字顯示:number_format
general = 'General' #對應Excel中的常規(guī) general_integer = '0' #不保留小數(shù)點 general_float = '0.00' #保留兩位小數(shù)點 percent = '0.0%' #百分數(shù) thousands_comma_sep = '#,##0' #千位分隔樣式 date = 'DD/MM/YY' #年月日 time_24_hours = 'HH:MM' #小時分鐘 time_24_hours_with_seconds = 'HH:MM:SS' #小時分鐘秒 time_12_hours = 'h:MM AM/PM' #12小時分鐘 上下午區(qū)分 time_12_hours_with_seconds = 'h:MM:SS AM/PM' #12小時分鐘秒 上下午區(qū)分 date_time = 'DD/MM/YY HH:MM' #年月日時分 date_time_with_seconds = 'DD/MM/YY HH:MM:SS' #年月日時分秒
實例:
sf.apply_column_style(cols_to_style=["col_1"],
styler_obj=Styler(number_format="0"),
style_header=True)
sf.apply_column_style(cols_to_style=["col_2"],
styler_obj=Styler(number_format="0.000"),
style_header=True)
sf.apply_column_style(cols_to_style=["col_3"],
styler_obj=Styler(number_format="0.0%"),
style_header=True)
h)條件格式:add_color_scale_conditional_formatting
num = 'num' #根據(jù)具體數(shù)值 percent = 'percent' #根據(jù)百分數(shù) max = 'max' #根據(jù)最大值 min = 'min' #根據(jù)最小值 formula = 'formula' #根據(jù)公式 percentile = 'percentile' #根據(jù)分位數(shù)
i)設置列寬:set_column_width\set_column_width_dict
sf.set_column_width(columns = ["col_1","col_2","col_3"],width=10)
sf.set_column_width_dict(col_width_dict = {"col_1":10,"col_2":20,"col_3":30})
j)設置行高:set_row_height\set_row_height_dict
最近需要做一些數(shù)據(jù)匯總,并存儲在Excel表格中,又想外觀看過去好看一點,那怎么辦呢,找到一個StyleFrame庫可以很容易的解決這問題。
正對pandas處理合并單元格暫未去測試,下次有空查閱一下資料看看能否解決。
利用pandas存儲數(shù)據(jù)的前提是先組織好數(shù)據(jù):
數(shù)據(jù)格式可以整理成以下格式:
- 數(shù)據(jù) = {表名:{‘列名稱’:數(shù)據(jù)(列表格式),…}}
- data = {‘test’:{‘name’:[‘小明’,‘小紅’,…]}}
為了方便調(diào)用數(shù)據(jù)存儲,封裝個類:
import pandas as pd
from StyleFrame import StyleFrame, Styler
class ExcelData(object):
'''
Excel操作
'''
def __init__(self):
self.sheet_data = {}
def addSheet(self, sheetname, DataFrame):
self.sheet_data[sheetname] = DataFrame
def readFile(self, filename, sheetnames):
'''
根據(jù)表名讀取數(shù)據(jù)-前提得先知道sheetname
'''
for sheet in sheetnames:
self.sheet_data[sheet] = pd.read_excel(filename, sheetname=sheet)
return self.sheet_data
def readDimFile(self, filename, sheetnames):
'''
讀取文件所有表數(shù)據(jù)
'''
data = pd.read_excel(filename, None)
return data
def addSumFile(self, public_asin):
datas = {'合計':[''],
'=SUM(C4:C'+ str(len(public_asin) + 5)+')':[''],
'=SUM(D4:D'+ str(len(public_asin) + 5)+')':[''],
'=IF(C2=0,0,ROUND(D2*100/C2,1))&"%"':[''],
'=SUM(F4:F'+ str(len(public_asin) + 5)+')':[''],
'=SUM(G4:G'+ str(len(public_asin) + 5)+')':[''],
'=IF(F2=0,0,ROUND(G2*100/F2,1))&"%"':[''],
'=SUM(I4:I'+ str(len(public_asin) + 5)+')':[''],
'=SUM(J4:J'+ str(len(public_asin) + 5)+')':[''],
'=IF(I2=0,0,ROUND(J2*100/I2,1))&"%"':[''],
'=SUM(L4:L'+ str(len(public_asin) + 5)+')':[''],
'=SUM(M4:M'+ str(len(public_asin) + 5)+')':[''],
'=IF(L2=0,0,ROUND(M2*100/L2,1))&"%"':[''],
'=IF(C2=0,0,ROUND((I2-C2)*100/C2,1))&"%"':[''],
'=IF(D2=0,0,ROUND((J2-D2)*100/D2,1))&"%"':[''],
'=IF(E2=0,0,ROUND((K2-E2)*100/E2,1))&"%"':[''],
'=IF(F2=0,0,ROUND((L2-F2)*100/F2,1))&"%"':[''],
'=IF(G2=0,0,ROUND((M2-G2)*100/G2,1))&"%"':[''],
'=IF(H2=0,0,ROUND((N2-H2)*100/H2,1))&"%"':['']}
col_dicts = ['合計', '=SUM(C4:C'+ str(len(public_asin) + 5)+')',
'=SUM(D4:D'+ str(len(public_asin) + 5)+')',
'=IF(C2=0,0,ROUND(D2*100/C2,1))&"%"',
'=SUM(F4:F'+ str(len(public_asin) + 5)+')',
'=SUM(G4:G'+ str(len(public_asin) + 5)+')',
'=IF(F2=0,0,ROUND(G2*100/F2,1))&"%"',
'=SUM(I4:I'+ str(len(public_asin) + 5)+')',
'=SUM(J4:J'+ str(len(public_asin) + 5)+')',
'=IF(I2=0,0,ROUND(J2*100/I2,1))&"%"',
'=SUM(L4:L'+ str(len(public_asin) + 5)+')',
'=SUM(M4:M'+ str(len(public_asin) + 5)+')',
'=IF(L2=0,0,ROUND(M2*100/L2,1))&"%"',
'=IF(C2=0,0,ROUND((I2-C2)*100/C2,1))&"%"',
'=IF(D2=0,0,ROUND((J2-D2)*100/D2,1))&"%"',
'=IF(E2=0,0,ROUND((K2-E2)*100/E2,1))&"%"',
'=IF(F2=0,0,ROUND((L2-F2)*100/F2,1))&"%"',
'=IF(G2=0,0,ROUND((M2-G2)*100/G2,1))&"%"',
'=IF(H2=0,0,ROUND((N2-H2)*100/H2,1))&"%"']
DataFrame = pd.DataFrame(data=datas)
DataFrame = DataFrame.ix[:, col_dicts]
return DataFrame
def saveFile(self, filename, sheet_names, cols_dict):
excel_writer = StyleFrame.ExcelWriter(filename)
for sheet in sheet_names:
#如果想在一個sheet表中寫入多次數(shù)據(jù),那么可以實例化多個sf對象,前提是寫到不同的單元格。
#如,需指定sheet_name為同一個表
# 以下的sf2的目的是想在已有的數(shù)據(jù)表頭部加一行合計匯總的數(shù)據(jù)
#sf2 = StyleFrame(self.addSumFile(self.sheet_data[sheet]['數(shù)據(jù)列']))
#sf2.to_excel(excel_writer, sheet_name=sheet, index=False, startcol=1, startrow=1)
#排序
#sort_data = self.sheet_data[sheet].sort_values(by=['排序列'], ascending=[True])
#sf = StyleFrame(self.sheet_data[sheet])
sf = StyleFrame(self.sheet_data[sheet])
key_len = get_maxlen(self.sheet_data[sheet]) # 獲取單元格最長字符串
style_cols = cols_dict[sheet] # 需要設置樣式的列名
for key in self.sheet_data[sheet]:
if key == '列名':
withs = key_len[key]*1.5 # 設置寬度:每個字符的1.5倍
else:
withs = key_len[key]*0.45 if key_len[key] > len(key) else len(key)*0.7
sf.set_column_width(columns=[key], width=withs) # 設置列寬
# 設置excel的樣式:styler_obj的樣式一列只能設置一次,所以重復設置會以后一個為準
sf.apply_column_style(cols_to_style=style_cols, styler_obj=Styler(font_size=10.5, bg_color='#DDD9C4'), style_header=True)
# apply_style_by_indexes:指定列添加樣式,以下表示'列名'這一列數(shù)值小于10的把字體標注為紅色
sf.apply_style_by_indexes(indexes_to_style=sf[sf['列名'] < '10'],cols_to_style=['列名'],styler_obj=Styler(font_color="#FF0000"))
# 格式化數(shù)字類型number_format:
# general = 'General' #對應Excel中的常規(guī)
# general_integer = '0' #不保留小數(shù)點
# general_float = '0.00' #保留兩位小數(shù)點
# percent = '0.0%' #百分數(shù)
# thousands_comma_sep = '#,##0' #千位分隔樣式
# date = 'DD/MM/YY' #年月日
# time_24_hours = 'HH:MM' #小時分鐘
# time_24_hours_with_seconds = 'HH:MM:SS' #小時分鐘秒
# time_12_hours = 'h:MM AM/PM' #12小時分鐘 上下午區(qū)分
# time_12_hours_with_seconds = 'h:MM:SS AM/PM' #12小時分鐘秒 上下午區(qū)分
# date_time = 'DD/MM/YY HH:MM' #年月日時分
# date_time_with_seconds = 'DD/MM/YY HH:MM:SS' #年月日時分秒
sf.apply_column_style(cols_to_style=["col_1"],
styler_obj=Styler(number_format="0"),
style_header=True)
sf.apply_column_style(cols_to_style=["col_2"],
styler_obj=Styler(number_format="0.000"),
style_header=True)
sf.apply_column_style(cols_to_style=["col_3"],
styler_obj=Styler(number_format="0.0%"),
style_header=True)
# row_to_add_filters=0 表示第一行加篩選條件,等于1則是第二行加篩選條件
# startrow表示起始行,2表示第三行開始填充,默認為0,第一行開始
sf.to_excel(excel_writer=excel_writer, row_to_add_filters=0, sheet_name=sheet, index=False, startrow=2)
excel_writer.save()
保存excel:傳入個sheetnames意在固定字表順序
def save_excel(datas, path, cols_dict, sheet_names):
excels = ExcelData()
for i in range(len(sheet_names)):
DataFrame = pd.DataFrame(data=datas[sheet_names[i]])
DataFrame = DataFrame.ix[:, list(cols_dict[str(sheet_names[i])])] # 首列按照list(cols_dict[str(sheet_names[i])])列表順序排序
excels.addSheet(sheet_names[i], DataFrame)
excels.saveFile(path, sheet_names, cols_dict)
獲取單元格最長字符串
def get_maxlen(datas):
b = {}
for data in datas:
b[data] = [len(str(d)) for d in datas[data]]
b[data] = max(b[data])
return b
樣式設置:
sf = StyleFrame(data) sf.apply_style_by_indexes(indexes_to_style=sf[sf['列名'] < -0.3], cols_to_style=['列名'], styler_obj=Styler(font_color="#FF0000", number_format="0.0%"))
sf[sf[‘列名’] < -0.2]這種無非也就是返回符合指定條件的索引列表,如果是單一的條件,沒有多重條件,這種寫法可以達到需求,如果想用多重條件,我一開始嘗試著:
sf[sf['列名'] < -0.2 , sf['列名'] > -0.3] sf[sf['列名'] < -0.2 and sf['列名'] > -0.3] sf[sf['列名'] < -0.2 & sf['列名'] > -0.3]
以上三種寫法均會報錯。
后面我就想都是傳入索引列表,那何不自己先把符合條件的索引先獲取,然后再傳入就可以了,所以修改后:
val_index_list = [] for idx,vals in enumerate(sheet_data['sheet名']['列名']): if vals < -0.2 and vals > -0.3: val_index_list.append(idx) sf.apply_style_by_indexes(indexes_to_style=val_index_list, cols_to_style=['列名'], styler_obj=Styler(font_color="#FF0000", number_format="0.0%"))
以下來一張結(jié)果圖:

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python調(diào)用Ollama庫本地大語言模型使用詳解
ollama是一個用于調(diào)用本地大語言模型的Python庫,提供了簡單、高效的API接口,下面文章詳細介紹了如何安裝、使用、設置自定義參數(shù)、集成流式生成、錯誤處理以及與其他工具集成,需要的朋友可以參考下2025-02-02
Python學習工具jupyter notebook安裝及用法解析
這篇文章主要介紹了Python學習工具jupyter notebook安裝及用法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10
python學習之panda數(shù)據(jù)分析核心支持庫
這篇文章主要給大家介紹了關于python學習之panda數(shù)據(jù)分析核心支持庫的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05
使用Arcgis做路徑規(guī)劃方式(使用python腳本調(diào)用)
本文介紹了如何使用ArcGIS和Python來解決鐵路路徑規(guī)劃問題,通過配置ArcGIS、導入路網(wǎng)數(shù)據(jù)和列車行駛點數(shù)據(jù)、處理線要素、構(gòu)建拓撲結(jié)構(gòu),可以使用Network?Analyst工具進行路徑分析,最后,通過Python腳本自動化處理大量數(shù)據(jù),生成最優(yōu)路徑2024-12-12

