Last active
May 31, 2017 13:40
-
-
Save yassineAlouini/d0f02b5476c42c9f99b036b5dd14acdd to your computer and use it in GitHub Desktop.
Save a Pandas DataFrame to Excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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