使用Pandas 绘制带样式的Excel

import pandas as pd
import openpyxl

#生成一个DataFrame
data= pd.DataFrame(data=np.random.randn(6,3),columns=["a",'b','c'])

#filename 保存的文件名
filename = 'test.xlsx'
writer = pd.ExcelWriter(filename,engine='openpyxl')
data.to_excel(writer, sheet_name='Sheet1',index=False)
worksheet = writer.sheets['Sheet1']

处理样式

#冻结首行
worksheet.freeze_panes = 'A2'
#冻结首行首列
worksheet.freeze_panes = 'B2'

更改每一列的数据格式:

#迭代器  取列
for i in worksheet.columns:
    i[0].fill = openpyxl.styles.PatternFill("solid", fgColor="FF9933")  #修改首行背景色
    i[0].font = openpyxl.styles.Font(name='Calibri',size=11,bold=True,italic=False,vertAlign=None,underline='none',strike=False,color='FF000000')   修改首行字体
    # 更改单元格格式
    for cell in i[1:]:
        cell.number_format = '#,##0_-'  #千位分割
        cell.number_format = '0.00%;-0.00%' #百分比
        cell.number_format = '$#,##0.00;-$#,##0.00'  #会计格式

按行修改样式:

#取行
qtyindex = None
for row in worksheet.rows:    #取列名为c的列
    for j in row:
        if j.value =='c':
            qtyindex = j.col_idx-1      
    break
a = 0
for row in worksheet.rows:
    a +=1
    if qtyindex and status_index and a>1:   #按行 列名为c 的值大于0时: 填充颜色
        if row[qtyindex].value > 0 :  
            for cell in row:
                cell.fill = openpyxl.styles.PatternFill("solid", fgColor="FFB6C1")

固定每一行宽度:

for i in range(1,data.shape[1]+1):   把列索引转换成 A,B...表示
        str = ''
        while (not (i // 26 == 0 and i % 26 == 0)):
            temp = 25
            if (i % 26 == 0):
                str += chr(temp + 65)
            else:
                str += chr(i % 26 - 1 + 65)
            i //= 26
        writer.sheets['Sheet1'].column_dimensions[str[::-1]].width = 16
#如果不转成'A,B,C,D..'保存时可能会出错

保存文件

writer.save()

你可能感兴趣的:(使用Pandas 绘制带样式的Excel)