Python Pandas XlsxWriter中心全面select

背景信息

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

我编写了代码,只要将其粘贴到xlsFilepath 。 现在,我只是简单地对文本进行硬编码,以便简化select,但理想情况下我要将其更改为Titlevariables。

 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() 

尝试

不工作

工作,但不居中

最后,我想坚持这个包,所以请不要推荐其他包。

它看起来像是我不知道的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() 

输出:

在这里输入图像说明

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