我正在尝试将熊猫的数据框输出到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()
我希望可以在最后两列中使用Excel的内置记帐格式,但是我不知道如何执行此操作。任何帮助表示赞赏。
答案 0 :(得分:3)
您步入正轨,您只需要在工作簿中添加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)
# 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()
有关格式的完整列表,请参见here。