跨越选择的Python Pandas XlsxWriter中心

时间:2016-04-15 18:50:41

标签: python excel pandas xlsxwriter

背景资讯

我有一个适用于创建合并标头的脚本,但我需要在选择中心而不是合并。我按照官方文档,但它不起作用。我已经尝试了大量可能的组合,其中一些我已经包含在下面的图片中。任何帮助将不胜感激。

代码

我编写了代码,您可以将其粘贴并运行,但xlsFilepath除外。就目前而言,为了简单起见,我只是将文本硬编码为选区的中心,但理想情况下我要将其更改为Title变量。

import pandas as pd
import numpy as np

#Create a random dataframe for this example
All_Columns_DF = pd.DataFrame(np.random.randn(100, 3), columns=['Title', 'Col_A' ,'Col_B'])

#Set file path for local machine
xlsFilepath = r'H:\myfile.xlsx'
#Create writer
writer = pd.ExcelWriter(xlsFilepath, engine='xlsxwriter')

#Write the DF to excel
All_Columns_DF.to_excel(writer, startrow = 1, sheet_name='Sheet1', index=False)
#Extract the header from the DF which I want to Center Across Selection in Row 1
Title_DF = All_Columns_DF[["Title"]]
Title_DF_Unique = Title_DF.drop_duplicates()
Title = Title_DF_Unique.iloc[0]['Title']

#Define WB and WS
workbook = writer.book
worksheet = writer.sheets['Sheet1']

#Start Formatting Attempt
format = workbook.add_format()
format.set_center_across()

''' Hard coding using row,col syntax does not work

worksheet.write(1, 1, 'Center across selection', format)
worksheet.write_blank(1, 2, '', format)
'''

'''Every combination of the below i try does not 
center across the columns. Ive put write_blank above
below, started at col A, B, etc, not thing ive tried
works
'''

worksheet.write_blank("B1:F1", '', format)
worksheet.write("A1", 'Center across selection', format)

writer.save()

尝试

Not Working

Works but not centered

最后,我想坚持使用此套餐,所以请不要推荐其他套餐。

1 个答案:

答案 0 :(得分:2)

看起来center_across()方法中存在一个我不知道的错误。我会修复它,但在此期间你可以使用set_align()方法获得相同的效果:

import pandas as pd

df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

writer = pd.ExcelWriter('pandas_centered.xlsx', engine='xlsxwriter')

df.to_excel(writer,
            startrow=1,
            sheet_name='Sheet1',
            index=False)

workbook = writer.book
worksheet = writer.sheets['Sheet1']

center_format = workbook.add_format()
center_format.set_align('center_across')


worksheet.write('A1', 'Center across selection', center_format)
worksheet.write('B1', '', center_format)
worksheet.write('C1', '', center_format)

writer.save()

输出:

enter image description here

更新:set_centered_across()问题现已在XlsxWriter 0.8.5版本中修复。