Python批量美化excel表的格式

作为例子,用前面爬取的携程游记数据,如下

只有第一个sheet,我提前把一些格式设置好,比如列宽啊,居中啊…
在这里插入图片描述
后面的,都是没有任何格式的,这里只有3个sheet表,但实际中可能遇到上百个这样的
在这里插入图片描述

最终效果:

在这里插入图片描述

然后把这种格式,应用在其他结构一样的sheet表中


代码:

xlwings能够在操作excel的时候,你可以实时看到效果

import xlwings as xw
from multiprocessing.dummy import Pool
from functools import partial


wb = xw.Book("携程.xlsx")  # 建立于sample.xlsx文件的连接
sheet = wb.sheets["sheet"] #打开sample.xlsx文件的sheet1
info = sheet.used_range
nrows = info.last_cell.row
ncolumns = info.last_cell.column



#设置第一个sheet,列宽提前弄好,后面的sheet都是用这个列宽
col_name = sheet[0,0:ncolumns].value
col_width = []
for i in range(ncolumns):
    col_width.append(sheet[0,i].column_width)
print('列宽:'+str(col_width))
print('列名:'+str(col_name))


def beautiful_sheet(sheet_name,col_name,col_width):
    info = sheet_name.used_range
    nrows = info.last_cell.row
    ncolumns = info.last_cell.column
    # 自定义列名
    sheet_name[0,0:ncolumns].value = col_name #更改标题行
    # 自定义边框
    # Borders(8)上边框、Borders(9)下边框、Borders(10)左边框、Borders(11)右边框
    # Borders(12)内横边框、Borders(11)内纵边框
    sheet_name[0:nrows,0:ncolumns].api.Borders(12).LineStyle = 2 #设置单元格横边框为细框线
    sheet_name[0:nrows,0:ncolumns].api.Borders(11).LineStyle = 2 #设置单元格竖边框为细框线
    # 自定义字体
    sheet_name[0:nrows,0:ncolumns].api.Font.Name = '微软雅黑'# 设置字体格式为微软雅黑
    sheet_name[0,0:ncolumns].api.Font.Size = 12# 设置字体格式为微软雅黑
    # 加粗
    sheet_name[0,0:ncolumns].api.Font.Bold = True
    # 居中
    sheet_name[0:nrows,0:ncolumns].api.HorizontalAlignment = -4108  #设置字体居中
    # 对某一列进行处理
    col_3 = sheet_name[1:nrows,3].value
    sheet_name[1:nrows,3].options(transpose=True).value = [i if i is None else i.replace('天','') for i in col_3]
    # 自定义列宽
    for i,item in enumerate(col_width): #列遍历,根据sample.xlsx中的列宽进行调整
        sheet_name[0,i].column_width = item
    # 颜色
    for i in range(nrows): ##行遍历
        if i==0:
            #设置标题背景颜色格式
            sheet_name[i, 0:ncolumns].color = [135,206,250]
        elif i%2 ==0:
            # 设置偶数行背景颜色
            sheet_name[i,0:ncolumns].color = [255,182,193]
    return None
    


# 批量应用
sheets_name= [st.name for st in wb.sheets]
# 固定参数
func = partial(beautiful_sheet, col_name=col_name,col_width=col_width)
for i in sheets_name:
    func(wb.sheets[i])

当然,还可以做更多其他操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值