Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom formatting when exporting to excel using pandas

How can I set different background color and font for some rows or columns when exporting a pandas DataFrame to Excel?

like image 339
user9624737 Avatar asked Aug 10 '19 08:08

user9624737


People also ask

How to export pandas Dataframe to excel?

You can export Pandas DataFrame to an Excel file using to_excel. Here is a template that you may apply in Python to export your DataFrame: df.to_excel(r'Path where the exported excel file will be storedFile Name.xlsx', index = False) And if you want to export your DataFrame to a specific Excel Sheet, then you may use this template:

How do I read data from an Excel file in pandas?

Read an Excel file into a pandas DataFrame. Read a comma-separated values (csv) file into DataFrame. For compatibility with to_csv () , to_excel serializes lists and dicts to strings before writing. Once a workbook has been saved it is not possible to write further data without rewriting the whole workbook.

Did you know pandas supports conditional formatting of DataFrames?

The Pandas library in Python has been predominantly used for data manipulation and analysis, but did you know that Pandas also allows for conditional formatting of DataFrames? Conditional formatting is a feature that allows you to apply specific formatting to cells that fulfill certain conditions.

How to set column width and format in pandas Excel?

# Set the column width and format. worksheet.set_column('B:B', 18, format1) # Set the format but not the column width. worksheet.set_column('C:C', None, format2) # Close the Pandas Excel writer and output the Excel file. writer.save()


1 Answers

https://pbpython.com/improve-pandas-excel-output.html has examples using xlsxwriter to customize the output file:

writer = pd.ExcelWriter('fancy.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name='report')

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

percent_fmt = workbook.add_format({'num_format': '0.0%',
                                   'bold': True
                                   #, 'bg_color': '#FFC7CE'
                                   })
worksheet.set_column('L:L', 12, percent_fmt)
writer.save()
like image 148
Nickolay Avatar answered Oct 23 '22 04:10

Nickolay