简体   繁体   English

如何在熊猫数据框上使用Excel内置格式(会计格式)

[英]How to use Excel built-in format(accounting format) on dataframe of Pandas

I am trying to output my dataframe in pandas to excel. 我试图以熊猫输出我的数据框以表现出色。

data = {'Names':['A', 'B', 'C', 'D'], Attending Cost’: [1, 1, 1, 1], 'Summary':[2, 2, 2, 2]}
data_2 = pd.DataFrame.from_dict(data)
writer = pd.ExcelWriter("test", engine='xlsxwriter')                
data_2.to_excel(writer, sheet_name='Sheet1', 
startrow=5)
writer.save()

I am hoping that I can use Excel's built-in accounting format on the last two columns, but I have no idea how to do this. 我希望可以在最后两列中使用Excel的内置记帐格式,但是我不知道如何执行此操作。 Any help is appreciated. 任何帮助表示赞赏。

You are on the right track, you just need to add excel's accountancy format to your workbook. 您走在正确的轨道上,您只需要在工作簿中添加excel的会计格式即可。 So continuing with your current code: 因此,继续您当前的代码:

data = {'Names':['A', 'B', 'C', 'D'], Attending Cost’: [1, 1, 1, 1], 'Summary':[2, 2, 2, 2]}
data_2 = pd.DataFrame.from_dict(data)
writer = pd.ExcelWriter("test", engine='xlsxwriter')                
data_2.to_excel(writer, sheet_name='Sheet1', 
startrow=5)

# get the clsx writer workbook and worksheet objects
workbook = writer.book
worksheet = writer.sheets['Sheet1']

# Add your accountancy format
format1 = workbook.add_format({'num_format': 44})

# Set format without assigning column width for columns C and D
worksheet.set_column('C:C', None, format1)
worksheet.set_column('D:D', None, format1)

# Close the pandas Excel Writer and output Excel File
writer.save()

A full list of the formats can be found here . 有关格式的完整列表,请参见此处

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

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