python操作excel

import openpyxl
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment

# 打开文件,遍历sheet
def open_file(file_path):
    wb=openpyxl.load_workbook(file_path)
    all_sheet_name=wb.sheetnames
    for item in all_sheet_name:
        sheet=wb[item]
        
        set_frist_row(sheet)
        set_table_title(sheet)
        set_column_width(sheet)
        set_other_row(sheet)
    return wb  
       
# 设置sheet标题
def set_frist_row(sheet):
    font =Font(size=24,bold=True,color='0000ff')
    alignment=Alignment(horizontal='center',vertical='center')
    fill=PatternFill('solid',fgColor='DDDDDD')
    sheet['A1'].fill=fill
    sheet['A1'].font=font
    sheet['A1'].alignment=alignment

# 设置表格标题
def set_table_title(sheet):
    font =Font(size=18,bold=True,color='0000ff',italic=True)
    alignment=Alignment(horizontal='center',vertical='center')
    sheet.row_dimensions[2].height=35
    for c in('A','B','C','D'):
        sheet[f'{c}{2}'].font=font
        sheet[f'{c}{2}'].alignment=alignment

# 设置列宽
def set_column_width(sheet):
    sheet.column_dimensions['A'].width=60
    sheet.column_dimensions['B'].width=120
    sheet.column_dimensions['C'].width=15
    sheet.column_dimensions['D'].width=20

# 设置其他行样式
def set_other_row(sheet):
    maxrow=sheet.max_row
    # 冻结
    sheet.freeze_panes="A3"
    # 边框
    side=Side(border_style="thin",color='000000')
    bd=Border(
        left=side,
        top=side,
        right=side,
        bottom=side,
    )
    if maxrow>=3:
        for i in range(3,maxrow+1):
            sheet.row_dimensions[i].height=35
            font =Font(size=14,color='000000')
            alignment=Alignment(vertical='center')
            for c in ('A','B','C','D'):
                sheet[f'{c}{i}'].font=font
                sheet[f'{c}{i}'].alignment=alignment
                sheet[f'{c}{i}'].border=bd

if __name__ == '__main__':
    file_path="./公司信息.xlsx"
    wb=open_file(file_path)
    wb.save(file_path)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值