Python3 pandas 自定义输出excel样式

本文介绍如何利用Python的Pandas库结合XlsxWriter库来生成格式美观的Excel文件,包括自定义列头格式、设置单元格背景颜色及自动换行等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import pandas as pd
import random
import numpy as np
import os


#
# data = [10, 20, 30, 40, 50, 60]
# df = pd.DataFrame({'Heading': data,
#                    'Longer heading that should be wrapped' : data})
df = pd.DataFrame(np.arange(16).reshape(4,4), columns=list('ABCD'))

BASEINPUT=os.path.dirname(__file__)
OUTPUTH=os.path.join(BASEINPUT,'result.xlsx')
writer = pd.ExcelWriter(OUTPUTH, engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object. Note that we turn off
# the default header and skip one row to allow us to insert a user defined
# header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=0,index=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a header format.
header_format = workbook.add_format({
    'bold': True, # 字体加粗
    'text_wrap': True, # 是否自动换行
    'valign': 'top',  #垂直对齐方式
    'align': 'right', # 水平对齐方式
    'fg_color': '#D7E4BC', # 单元格背景颜色
    'border': 2}) # 单元格边框宽度


yellow = workbook.add_format({'fg_color': '#FFEE99'})
red=workbook.add_format({'fg_color': '#2dB054'})

# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
    if col_num%2==0:
        worksheet.write(0, col_num, value, header_format)
    else:
        worksheet.write(0, col_num, value, yellow)

# Write the row with the defined format.
for index, value in df.iterrows():
    print(index," -- > ",value.values)
    if index % 2 == 0:
        worksheet.write(index+1, 0, value[0], header_format)
    else:
        worksheet.write(index+1, 0, value[0], yellow)

worksheet.set_column("A:C", 16)
format2 = workbook.add_format({'bold':  True, 'align': 'vcenter', 'valign': 'top', 'text_wrap': True})
worksheet.set_row(0, cell_format=format2)
# Close the Pandas Excel writer and output the Excel file.
writer.save()

参考链接:https://xlsxwriter.readthedocs.io/example_pandas_column_formats.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值