Mo Azim
Mo Azim

Reputation: 13

How do I save a pandas df to excel sheet then format it?

import pandas as pd

from datetime import datetime, date

df = pd.DataFrame({'Date and time': [datetime(2015, 1, 1, 11, 30, 55),
                                 datetime(2015, 1, 2, 1,  20, 33),
                                 datetime(2015, 1, 3, 11, 10    ),
                                 datetime(2015, 1, 4, 16, 45, 35),
                                 datetime(2015, 1, 5, 12, 10, 15)],
                   'Dates only':    [date(2015, 2, 1),
                                 date(2015, 2, 2),
                                 date(2015, 2, 3),
                                 date(2015, 2, 4),
                                 date(2015, 2, 5)],
               })

writer = pd.ExcelWriter("pandas_datetime_format.xlsx",
                    engine='xlsxwriter',
                    datetime_format='mmm d yyyy hh:mm:ss',
                    date_format='mmmm dd yyyy')

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

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

format_bc = workbook.add_format({
    'font_name': 'Arial',
    'font_size' : 14,
    'font_color': 'white',
    'bold': 0,
    'border': 1,
    'align': 'left',
    'valign': 'vcenter',
    'text_wrap': 1,
    'fg_color': '#005581'})
worksheet.set_column('B:C', 20, format_bc)
writer.save()

The above code was expected to generated a formatted excel sheet, with the columns B and B having blue background and other aspects specified in format_bc. Instead I received a file shown in the image below.

Not formatting the desired cells

Is there a way to write a dataframe to an excel sheet with formatting?

Upvotes: 1

Views: 1747

Answers (1)

smallwat3r
smallwat3r

Reputation: 1117

Unfortunately as seen here https://github.com/jmcnamara/XlsxWriter/issues/336 , this is not possible to format date and datetime values with XlsxWriter.

What you could do instead is add df = df.astype(str) to change your dataframe formats from date / datetime to string.

df = pd.DataFrame(
    {
        'Date and time': [
            datetime(2015, 1, 1, 11, 30, 55),
            datetime(2015, 1, 2, 1,  20, 33),
            [ ... ]
        ],
        'Dates only': [
            date(2015, 2, 1),
            date(2015, 2, 2),
            [ ... ]
        ]
    }
)

df = df.astype(str)

writer = pd.ExcelWriter("pandas_datetime_format.xlsx",
                        engine='xlsxwriter',
                        [ ... ])

[ ... ]

Outputs :

enter image description here

Note that if you want the headers to be overwritten with the new format, add to the beginning of your code:

import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None

Upvotes: 3

Related Questions