简体   繁体   English

如何使用python中的xlsx包格式化excel中的特定单元格

[英]how to format specific cells in excel using xlsx package in python

I have a pandas df which I am formatting using xlsx package currently I have the option to format an entire row or column using xlsx but not specific cells also I would like to insert few lines in between the DF.我有一个pandas df,我正在使用xlsx 包进行格式化,目前我可以选择使用xlsx 格式化整个行或列,但不是特定的单元格,我也想在DF 之间插入几行。

Image attached how I want the excel file to look.附上我希望 excel 文件的外观的图像。

The below code gives me the file in the 1st part of the image.下面的代码给了我图像第一部分的文件。 I need to do some more formatting like inserting new lines and making D13 and E13 in italics.我需要做一些更多的格式化,比如插入新行并用斜体制作 D13 和 E13。 在此处输入图片说明

writer = pd.ExcelWriter('Sample Report Test.xlsx' , engine='xlsxwriter')
df.to_excel(writer , index= False , sheet_name='Sample Report')

workbook = writer.book
worksheet = writer.sheets['Sample Report']

money_fmt = workbook.add_format({'num_format':'$#,##0' ,  'font_name':'Batang' })
font_fmt = workbook.add_format({'font_name':'Batang' , 'bold':True })
tot_fmt = workbook.add_format({'num_format':'$#,##0' ,  'font_name':'Batang' ,  'bold':True })

worksheet.set_column('A:B' , 25 , font_fmt)
worksheet.set_column('C:P' , 15 , money_fmt)
worksheet.set_row(4, None , tot_fmt)
worksheet.set_row(7 , None , tot_fmt)

writer.save()

You can insert more than one dataframe, with offsets, into an XlsxWriter file.您可以在 XlsxWriter 文件中插入多个带有偏移量的数据帧。 See this example from the docs.请参阅文档中的此示例

It isn't possible to format cells after they are written (apart from column/row formats, see this example ).写入后无法格式化单元格(除了列/行格式,请参阅此示例)。

If you need very fine grained formatting you would be best to just use XlsxWriter directly with the data from the dataframe.如果您需要非常细粒度的格式,您最好直接将 XlsxWriter 与数据帧中的数据一起使用。

Some people use conditional formatting in XlsxWriter to get the effect they need, like this SO answer .有些人在 XlsxWriter 中使用条件格式来获得他们需要的效果,就像这个SO answer However, that isn't applicable to single cells.但是,这不适用于单个细胞。

Try this:尝试这个:

money_italic_fmt = workbook.add_format({'num_format':'$#,##0',
                                        'font_name':'Batang',
                                        'italic':True})
worksheet.write(12, # <-- The cell row (zero indexed).
                3,  # <-- The cell column (zero indexed).
                13, # <-- Value to write
                money_italic_fmt  # <-- Format
)

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

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