python 给excel添加样式

openpyxl填充背景和字体颜色

加载已存在的excel文件进行处理


import openpyxl
import openpyxl
from openpyxl.styles import Font  # 导入字体模块
from openpyxl.styles import PatternFill  # 导入填充模块

def Textcolor(file_name,title):
    wk = openpyxl.load_workbook(file_name)  # 加载已经存在的excel
    sheet1 = wk[title]#wk[wk_name[0]]#title名称
    for i in range(10):
        #Color=['c6efce','006100']#绿
        #Color = ['ffc7ce', '9c0006']  #红
        #Color = ['ffeb9c', '9c6500']  # 黄
        Color = ['ffffff', '000000']  # 黑白

        fille = PatternFill('solid', fgColor=Color[0])  # 设置填充颜色为 橙色
        font = Font(u'微软雅黑', size=11, bold=True, italic=False, strike=False, color=Color[1])  # 设置字体样式
        sheet1.cell(row=i + 2, column=8, value="").fill = fille  # 序列
        sheet1.cell(row=i + 2, column=8, value="哈哈").font =font # 序列

    wk.save(file_name)  # 保存excel



file_name, title = 's.xlsx', 'Sheet1'
Textcolor(file_name,title)

image

更详细的转载博客地址

直接在写入的时候进行处理

# PatternFill 设置单元格背景
from openpyxl.styles import PatternFill
# Font设置字体
from openpyxl.styles import Font

# 设置Excel框样式
def excel_style(params1):
    if '一致' == params1:
        # 3-设置样式,并且加载到对应单元格 颜色需要使用颜色的十六进制表示
        fill = PatternFill("solid", fgColor="33CC33")  # 绿色
    else:
        fill = PatternFill("solid", fgColor="FF0000")  # 红色
    return fill


# 设置Excel文字样式
def excel_fout(params1):
    if '一致' == params1:
        # 3-设置样式,并且加载到对应单元格
        font = Font(u'微软雅黑', size=11, bold=True, italic=False, strike=False, color="33CC33")
    else:
        font = Font(u'微软雅黑', size=11, bold=True, italic=False, strike=False, color="FF0000")
    return font


def saveExcels(excelBodys, same_inv_excelBodys, fileName):
    logger.info('开始数据保存=======================================================================')
    mywb = openpyxl.Workbook()
    table = mywb["Sheet"]
    # 第一行创建标题
    table['A1'] = '货品编码'
    table['G1'] = 'WMS与OFS'
    table['H1'] = 'WMS与OBC'
    for excelBody in excelBodys:
        num = excelBody['excelLine']
        itemCode = excelBody['itemCode']
        table['A' + str(num)] = itemCode
        table['G' + str(num)] = wmsToOfs
        table['H' + str(num)] = wmsToObc
        # 设置单元格颜色
        table['G' + str(num)].font = excel_fout(wmsToOfs)
        table['H' + str(num)].font = excel_fout(wmsToObc)
    mywb.close()
    mywb.save(fileName + '.xlsx')

if __name__ == "__main__":
    fileName = './source_file/' + str(datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S"))
    saveExcels([],[],fileName)

十六进制颜色表达式

posted @ 2021-10-23 22:32  darling331  阅读(300)  评论(0编辑  收藏  举报