Last active
September 13, 2019 20:36
-
-
Save NicholasBallard/1a7764897e3d5d72e942923205d29d69 to your computer and use it in GitHub Desktop.
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
import os | |
import pandas as pd | |
import xlsxwriter | |
from xlsxwriter.utility import xl_col_to_name | |
def set_column(df: 'dataframe', worksheet: 'a pd.Excelwriter sheet', cols: list, format: 'excel format to use', col_width: int = None) -> None: | |
""" sets column by index, the column's position in the dataframe """ | |
idx = [df.columns.get_loc(c) for c in cols if c in df] | |
for i in idx: | |
# set the column width and format | |
col = xl_col_to_name(i) | |
worksheet.set_column( | |
f'{col}:{col}', | |
col_width, | |
format) | |
def format(df: 'affiliate revenue stats dataframe', writer: 'pandas.ExcelWriter object', sheetname: str, ) -> 'pd.ExcelWriter': | |
''' | |
formats affiliate revenue stats excel worksheet with currency and percentage formatting | |
''' | |
# conv df to xslxwriter excel object | |
df.to_excel( | |
excel_writer=writer, | |
sheet_name=sheetname, | |
index=False, | |
) | |
# get the xlsxwriter workbook and worksheet objects | |
workbook = writer.book | |
worksheet = writer.sheets[sheetname] | |
# add format cells written | |
pct_fmt = workbook.add_format({ | |
'num_format': '0.0%', | |
}) | |
money_fmt = workbook.add_format({ | |
'num_format': '$#,##0.00', | |
}) | |
pct_cols = df.filter(regex='Rate|Margin') | |
money_cols = df.filter(regex='Revenue|RPC|Cost') | |
set_column(df, worksheet, pct_cols, pct_fmt) | |
set_column(df, worksheet, money_cols, money_fmt) | |
return writer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Yanan! Here's a module you can put in the same directory as the Jupyter notebook you are writing the spreadsheets with. Here is how you would use it:
Then where you iterate through the affiliate list ...