将列转换为财务会计格式工作表条件格式

时间:2019-03-11 18:47:15

标签: python excel pandas

我有一个熊猫数据框,如下所示:

A       B              C          
SDF     899501607.2   -26152567.7
ISB     464284188.7   -20278910.23
ADF     0                         
SDF     3978706912   -57575106    
All     5342492708   -104006583.9

使用工作表条件格式,我要以以下格式显示数字(四舍五入,逗号,(),$为负)

A       B                 C        
SDF     $ 899,501,607     $(26,152,568) 
ISB     $ 464,284,189     $(20,278,910) 
ADF     $ 0               $0           
SDF     $ 3,978,706,912   $(57,575,106)
All     $ 5,342,492,708   $(104,006,584)

2 个答案:

答案 0 :(得分:2)

假设你有

import io

df = pd.read_table(io.StringIO('''\
A       B              C          
SDF     899501607.2   -26152567.7
ISB     464284188.7   -20278910.23
ADF     0                         
SDF     3978706912   -57575106    
All     5342492708   -104006583.9'''), delim_whitespace=True)

然后您可以使用pd.ExcelWriterhttps://j11y.io/javascript/truthy-falsey/来获取

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

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

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

format1 = workbook.add_format({'num_format': '$#,##0.00_);[Red]($#,##0.00)'})
format2 = workbook.add_format({'num_format': '$#,##0.00_);[Red]($#,##0.00)'})


worksheet.set_column('B:B', 18, format1)
worksheet.set_column('C:C', 18, format2)
writer.save()

这将导致

reference the documentation

答案 1 :(得分:1)

我注意到您问过条件格式,但也许您可以考虑使用像这样的custom number format

$#,##0;[Red]$(#,##0)

哪个给:

Custom format sample

要创建自定义格式,请右键单击单元格,选择Format cells...并输入以下规则:

Custom format setting