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