python之如何使用openpyxl設(shè)置單元格樣式
引言
在pandas保存多個excel表格的時候,有時單元格中的內(nèi)容很多,預(yù)覽的時候不方便查看,這時候我們需要修改單元格的寬高及換行顯示
下面直接來看代碼
import pandas as pd import datetime df = pd.read_excel('測試.xlsx') grouped = df.groupby(['部門']) current_time = datetime.datetime.now() current_time = current_time.strftime('%m%d') print(current_time) name_list = [] for dtype,group in grouped: if "/" in dtype: dtype = dtype.replace("/","-") group.to_excel(f"./demand/{dtype}{current_time}.xlsx",index = False) name_list.append(f"./demand/{dtype}{current_time}.xlsx")
這段代碼先將測試表格拆分為多個表格,并且拿到各部門的表格name。
def format_xlsx(file_path): import os from openpyxl import load_workbook from openpyxl.utils import get_column_letter from openpyxl.styles import PatternFill, Alignment, Side, Border from openpyxl.styles import Font, Color, colors, Border, Side, Alignment wb = load_workbook(file_path) # 打開工作表 ws = wb.active #設(shè)置單元格邊框的線條樣式 border_set = Border(left=Side(style='thin', color=colors.BLACK), # 左邊框 right=Side(style='thin', color=colors.BLACK), # 右邊框 top=Side(style='thin', color=colors.BLACK), # 上邊框 bottom=Side(style='thin', color=colors.BLACK)) # 下邊框 #設(shè)置單元格內(nèi)容對齊方式 for i in ws: for j in i: # print(j,type(j)) j.alignment = Alignment(horizontal='center', vertical='center',wrapText = True) j.border = border_set #設(shè)置單元格寬高 width = 50 height = 80 # height = width * (2.2862 / 0.3612) for i in range(2, ws.max_row+1): ws.row_dimensions[i].height = height for i in range(1, ws.max_column+1): ws.column_dimensions[get_column_letter(i)].width = width wb.save(file_path)
然后定義一個format函數(shù),來對sheet頁進行格式化。
ws為worksheet,即單個sheet頁,嵌套遍歷時,i為列遍歷的整列[“A”]、[“B”]、[“C”]…然后再行遍歷,得到的就是[“A1”][“B1”][“C1”]…等所有的單元格cell。
這里設(shè)置了三個參數(shù),水平居中”horizontal“,垂直居中”vertical”,還有一個換行顯示“wrapText”。
然后是設(shè)置單元格的寬高
分別循環(huán)去獲取有數(shù)據(jù)的單元格的最大長度,注意:這里的openpyxl庫循環(huán)遍歷時首個元素的下標為1而不是0,而行我們是從第二行開始設(shè)置的,原因是表頭一般都會單獨設(shè)置醒目樣式以區(qū)分表體。
下面是操作截圖
初始表
生成表
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Django中如何使用celery異步發(fā)送短信驗證碼詳解
Celery是Python開發(fā)的分布式任務(wù)調(diào)度模塊,這篇文章主要給大家介紹了關(guān)于Django中如何使用celery異步發(fā)送短信驗證碼的相關(guān)資料,主要內(nèi)容包括基礎(chǔ)介紹、工作原理、完整代碼等方面,需要的朋友可以參考下2021-09-09python中if的基礎(chǔ)用法(if?else和if?not)
if在Python中用作某個條件或值的判斷,下面這篇文章主要給大家介紹了關(guān)于python中if的基礎(chǔ)用法,主要包括if?else和if?not,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-09-09python面向?qū)ο髮崿F(xiàn)名片管理系統(tǒng)文件版
這篇文章主要為大家詳細介紹了python面向?qū)ο髮崿F(xiàn)名片管理系統(tǒng)文件版,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04django queryset 去重 .distinct()說明
這篇文章主要介紹了django queryset 去重 .distinct()說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python的數(shù)據(jù)結(jié)構(gòu)與算法的隊列詳解(3)
這篇文章主要為大家詳細介紹了Python的隊列,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03