Cl4u
Cl4u

Reputation: 35

Error on saving date format in file with pandas ExcelWriter

I'm trying to save an Excel file with date format and I got error.

Here is my code:

import pandas as pd
from datetime import datetime, date

df=dataframe with two columns: created_at (date format), name (number format)

writer = pd.ExcelWriter('graph_data.xlsx',engine='xlsxwriter',date_format='mm dd yyyy')

pd.DataFrame(df).to_excel(writer, 'Name') 

writer.save()

I obtain an Excel like following:

enter image description here

I can format the cells manually but I would like to format them directly in the code?

Upvotes: 0

Views: 1476

Answers (1)

alfonso.kim
alfonso.kim

Reputation: 2900

From the docs:

If you require very controlled formatting of the dataframe output then you would probably be better off using Xlsxwriter directly with raw data taken from Pandas.

Then I suggest to do something like this:

workbook  = writer.book
worksheet = writer.sheets['Name']
worksheet.set_column('A:A', 20)  # Assuming is the first column
writer.save()

Complete example here

Upvotes: 2

Related Questions