一、为什么要搞
手头有Excel文档,其中记录了会员的一些基础信息。现在需要根据现有信息,自动生成会员的生日和邮编,并美化表格的样式,使其更加清晰易读
注:文中使用的相关数据均为Python的faker模块生成的虚拟数据
原表格示例如下:
二、准备如何搞
可根据原表格的身份证列提取出生日
邮编/地址列格式如:河北省秀华县闵行乌鲁木齐路s座 160262
可根据邮编/地址列拆分出地址和邮编
数据拆分和提取使用pandas模块;表格样式美化使用openpyxl模块
pip install pandas
pip install openpyxl
三、说搞咱就搞
拆分提取数据
pandas读取excel,根据“身份证”列提取出生日,根据“地址/邮编”列拆分出地址和邮编,移除原“地址/邮编”列
import pandas as pd
def data_split(file_path):
"""
拆分excel数据
"""
df = pd.read_excel(file_path) # pandas读取excel
df['生日'] = df['身份证'].apply(lambda x: f"{x[6:14][0:4]}/{x[6:14][4:6]}/{x[6:14][6:8]}") # 根据身份证提取生日
df[['地址', '邮编']] = df['地址/邮编'].str.split(' ', expand=True) # 根据“地址/邮编”列拆分出地址和邮编
df = df.drop(['地址/邮编'], axis=1) # 删除“地址/邮编”列
df.to_excel(file_path, index=False) # 保存到原文件
if __name__ == "__main__":
file = 'test_data_member_info.xlsx' # excel文件路径
data_split(file) # 拆分提取数据
运行结果:
隔行填充颜色
openpyxl的styles.PatternFill填充表头和表格颜色
from openpyxl.styles import PatternFill
def set_fg_color(ws, color='BBFFFF'):
"""
设置表格隔行填充颜色
"""
# 设置表头填充颜色
fg_color_head = PatternFill('solid', fgColor='33CCFF') # 表头填充颜色--16进制
for c in range(1, ws.max_column + 1): # 遍历所有列
ws.cell(1, c).fill = fg_color_head # 设置单元格填充颜色
# 设置表格填充颜色
fg_color = PatternFill('solid', fgColor=color) # 表格填充颜色--16进制
for r in range(1, ws.max_row + 1): # 遍历所有行
if r % 2 == 0: # 偶数行
for c in range(1, ws.max_column + 1): # 遍历所有列
ws.cell(r, c).fill = fg_color # 设置单元格填充颜色
设置居中对齐
openpyxl的styles.Alignment设置表格内容居中对齐
from openpyxl.styles import Alignment
def set_alignment(ws, align='center', wrap=False):
"""
设置对齐方式
"""
align = Alignment(horizontal=align, vertical=align, wrapText=wrap) # 居中对齐,不自动换行
for r in range(1, ws.max_row + 1): # 遍历所有行
for c in range(1, ws.max_column + 1): # 遍历所有列
ws.cell(r, c).alignment = align
添加表格边框
openpyxl的styles.Border和styles.Side设置表格的边框
from openpyxl.styles import Border, Side
def set_border(ws):
"""
设置表格边框
"""
border = Border(left=Side(border_style='thin'), right=Side(border_style='thin'), top=Side(border_style='thin'),
bottom=Side(border_style='thin')) # 边框样式--所有框线
for r in range(1, ws.max_row + 1):
for c in range(1, ws.max_column + 1):
ws.cell(r, c).border = border
自动调整列宽
pandas读取excel,获取列的长度的最大值,openpyxl.utils.get_column_letter获取列名(字母),再通过column_dimensions设置列宽
import pandas as pd
from openpyxl.utils import get_column_letter
def set_column_width(file_path, ws):
"""
根据内容长度自动调整列宽
"""
df = pd.read_excel(file_path) # pandas读取excel
if not df.empty: # 若df不为空
for c in df.columns: # 遍历所有列
col_index = list(df.columns).index(c) # 列的下标
col_letter = get_column_letter(col_index + 1) # 列名--字母
col_length = df[c].apply(lambda x: len(str(x).encode())).max() # 获取列长度的最大值
ws.column_dimensions[col_letter].width = col_length + 3 # 设置列宽=列长度最大值+3
调用方法运行
指定excel文件路径,openpyxl.load_workbook打开工作簿,调用以上方法,保存excel
if __name__ == "__main__":
file = 'test_data_member_info.xlsx' # excel文件路径
data_split(file) # 拆分excel数据
work_book = load_workbook(file) # excel工作簿
sheet_name = work_book.sheetnames[0] # 第一个sheet名称
work_sheet = work_book[sheet_name] # 第一个sheet工作表
set_fg_color(work_sheet) # 隔行填充颜色
set_alignment(work_sheet) # 设置居中对齐
set_border(work_sheet) # 添加表格边框
set_column_width(file, work_sheet) # 自动调整列宽
work_book.save('modified_test_data.xlsx') # 保存excel
运行结果: