xlsxwriter多种格式添加格式化方法

Add format method in xlsxwriter multiple formats

我正在尝试以下代码,它运行良好。但我想知道是否有一种简短的方法来处理 xlsxwriter 包中的添加格式功能。 这是更多说明的代码

import pandas as pd
import xlsxwriter

writer = pd.ExcelWriter('pandas_excel.xlsx', engine='xlsxwriter')
new_df.to_excel(writer, sheet_name='Sheet1')

workbook  = writer.book

format_right_to_left = workbook.add_format()
format_right_to_left.set_reading_order(2)

myformat = workbook.add_format()
myformat.set_reading_order(2)
myformat.set_align('center')
myformat.set_align('vcenter')

worksheet = writer.sheets['Sheet1']
worksheet.right_to_left()

worksheet.set_column('B:G', 12, myformat)
worksheet.set_column('A:A', 16, myformat)
writer.save()
writer.close()

在代码中我有那些添加格式的行

myformat = workbook.add_format()
myformat.set_reading_order(2)
myformat.set_align('center')
myformat.set_align('vcenter')

我的问题是如何缩短这些行以便更加灵活并且能够以简单的方式添加越来越多的格式?

您可以将属性作为字典传递给 add_format()

my_format = workbook.add_format({'reading_order':2, 'align':'center', 'valign':'vcenter'})

你可以read more here

编辑:完整的工作示例,带边框

import pandas as pd
import xlsxwriter

data = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=data)

with pd.ExcelWriter('pandas_excel.xlsx', engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='Sheet1')
    workbook  = writer.book
    my_format = workbook.add_format({'reading_order':2, 'align':'center', 'valign':'vcenter', 'border':1})
    worksheet = writer.sheets['Sheet1']
    worksheet.set_column('B:G', 12, my_format)
    worksheet.set_column('A:A', 16, my_format)