Skip to content

Instantly share code, notes, and snippets.

@yassineAlouini
Last active May 31, 2017 13:40
Show Gist options
  • Save yassineAlouini/d0f02b5476c42c9f99b036b5dd14acdd to your computer and use it in GitHub Desktop.
Save yassineAlouini/d0f02b5476c42c9f99b036b5dd14acdd to your computer and use it in GitHub Desktop.
Save a Pandas DataFrame to Excel
# You need to install xlsxwriter: pip install xlsxwriter
import pandas as pd
import StringIO
def save_df_to_xls(input_df, fp, sheet_name='report'):
df = input_df.copy()
writer = pd.ExcelWriter(fp, engine='xlsxwriter',
datetime_format='d/mm/yyyy') # Datatime format for french users
df.to_excel(writer, index=False, sheet_name=sheet_name, encoding='utf-8) # Encoding for french users
writer.save()
df = pd.DataFrame({'date': pd.date_range('2017-1-1', '2017-1-10')})
# Example: Save to a path
save_df_to_xls(df, '/tmp/example_report.xls')
# Example: Save to a string
output = StringIO.StringIO()
save_df_to_xls(df, output)
xlsx_data = output.getvalue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment