I am working on a pandas dataframe with a varying number of columns. I want to parse it to Excel using xlsxWriter and create a worksheet table. Due to the varying number of columns I created a list comprehension for the column names when creating the table. (Here I just created a sample dataframe so dont get confused)
Can I somehow add additional optional parameters in that list comprehension to adjust the format of each header in the table? For instance, indent each header by 2 from the left? Or if possible add different formats to each column depending on the name of the header.
Below is the code I have so far:
writer = pd.ExcelWriter('pandas_table.xlsx', engine='xlsxwriter')
data = [
['Apples', 10000, 5000, 8000, 6000, 8000],
['Pears', 2000, 3000, 4000, 5000, 8000],
['Bananas', 6000, 6000, 6500, 600, 80000],
['Oranges', 500, 300, 200, 700, 8000],
]
#transform the list of values into a dataframe
df = pd.DataFrame(data = data, columns = ['Product', 'Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4', 'wtf' ])
#assign the dataframe to the worksheet Sheet1
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False, index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
#define the length of the dataframe for the table format
(max_row, max_col) = df.shape
#list comprehension for the optional columns parameter in add_table
col_settings = [{'header': column} for column in df.columns]
worksheet.add_table(0, 0, max_row, max_col - 1, {'columns' : col_settings})
To format single columns I did this little workaround but maybe you know also a smoother way to do that.
for i, col in enumerate(df.columns):
if col == 'Quarter 2':
worksheet.set_column(i, i, 18, currency_format)
else:
worksheet.set_column(i, i, 18)