简体   繁体   English

使用 Python 对齐 Excel 工作表中的某些列

[英]Aligning some of the columns in Excel Worksheet using Python

I am having trouble aligning the columns of an Excel Worksheet using xlsxWriter.我在使用 xlsxWriter 对齐 Excel 工作表的列时遇到问题。 For further clarity here is the data-frame为了进一步清楚,这里是数据框

   Name        Employee ID      Year
John Miller    2014108          2014
Sarah Jones    2011548          2011
Jake Kenedy    2010546          2010

I am trying to align the Name column so that the values are on the left instead of being centred我正在尝试对齐 Name 列,以便值在左侧而不是居中

I tried this我试过这个

workbook = writer.book
cell_format = workbook.add_format()
cell_format.set_align('left')

However, nothing happened.然而,什么也没发生。 Any suggestions would be greatly appreciated.任何建议将不胜感激。

You need to actually apply the formatting the name column.您需要实际应用名称列的格式。

df = pd.DataFrame ({'Name': ['J Miller', 'S Jones', 'J Kenedy'],
                    'Employee ID': [1,2,3],
                    'Year': [2014, 2011, 2010]})

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

# Add your dataframe to the writer
df.to_excel(writer, sheet_name='Sheet1')

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

new_format = workbook.add_format()
new_format.set_align('left')

# Apply new format to name column, which will be column C.
worksheet.set_column('C:C', 10, new_format)
writer.save()

Might be worth a look: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html可能值得一看: http : //xlsxwriter.readthedocs.io/example_pandas_column_formats.html

I had the same issue related to the index.我有与索引相关的相同问题。 My dataframe had the first column of type string as the index.我的数据框将字符串类型的第一列作为索引。 It appears the index cannot be reformatted using xlsxwriter .似乎无法使用xlsxwriter重新格式化xlsxwriter To get around this I tried the following in this order:为了解决这个问题,我按以下顺序尝试了以下操作:

df.reset_index(inplace=True)
df.to_excel(writer, sheet_name='Sheet1',index=False)

Then the formatting functions worked.然后格式化功能起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM