I'm using the below class I've written to try and dynamically create a single Excel file with several worksheets where there is a printed dataframe and a column chart in each worksheet.
Interacton with the code (seen below) should function where you initiate a workbook:
test = Workbook('Test Workbook')
And then, you can add as many charts as you want:
test.add_chart(df, 'Df Title', 1)
test.add_chart(df2, 'Df2 Title', 1)
And then you produce the workbook:
test.produce()
Input dataframes have headers. First column is text categories, subsequent columns (of varying number) are data in the form of decimals, that are to be graphed as percents.
THE ISSUE: The code works fairly well, and seems to produce all of the worksheets separately with charts, BUT some of the charts appear as "not referenced", meaning that when I click on a bar in the column chart, it does not highlight the source data. Some of the charts produced with the code, DO reference appropriately, so I am not sure where the issue is, and there is not an obvious trend.
import xlsxwriter
import pandas as pd
class Workbook:
def __init__(self, workbook_name):
self.workbook_name = workbook_name
self.workbook = xlsxwriter.Workbook(str(self.workbook_name) + '.xlsx')
self.letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']
def produce(self):
self.workbook.close()
print 'Created ' + str(self.workbook_name) + '.xlsx'
def print_frame(self, worksheet, dataframe, df_width, start_data_index):
col_as_lists = []
col_names = list(dataframe.columns.values)
# loops through columns in df and converts to list
for n in range(0, df_width):
col_n = dataframe[col_names[n]].tolist()
# checks to see if column has numbers, if so -> convert to float!
if n < start_data_index:
col_n.insert(0, col_names[n])
elif self.is_number(col_n[0]):
convert = col_n[0:]
convert = [float(x) for x in convert]
convert.insert(0, col_names[n])
col_n = convert
else:
col_n.insert(0, col_names[n])
col_as_lists.append(col_n)
# Prints each list into the worksheet.
worksheet.write_column(self.letters[n] + '1', col_as_lists[n])
#Formats numerical data as percentage
percentformat = self.workbook.add_format({'num_format': '0%'})
worksheet.set_column(self.letters[start_data_index] + ':' + self.letters[df_width], None, percentformat)
def add_chart(self, dataframe, tab_name, start_data_index):
df_width = len(dataframe.columns)
worksheet = self.workbook.add_worksheet(tab_name)
self.print_frame(worksheet, dataframe, df_width, start_data_index)
chart = self.workbook.add_chart({'type': 'column'})
df_length = (len(dataframe.index))
for n in range(start_data_index, df_width):
chart.add_series({
'name': '=' + tab_name +'!$' + self.letters[n] + '$1',
'categories': '=' + tab_name +'!$' + self.letters[start_data_index - 1] + '$2:$'+ self.letters[start_data_index - 1] + '$' + str(df_length + 1),
'values': '=' + tab_name +'!$' + self.letters[n] + '$2:$'+ self.letters[n] + '$' + str(df_length + 1),
'fill': {'color': '#FFB11E'},
'data_labels': {'value': True, 'center': True}
})
chart.set_title({'name': tab_name})
chart.set_x_axis({'major_gridlines': {'visible': False}})
chart.set_y_axis({'major_gridlines': {'visible': False}, 'max': .70})
worksheet.insert_chart(self.letters[df_width + 2] + '2', chart)
return
def is_number(self, s):
""" Function used to help with detecting and converting floats
from string to number data types."""
try:
float(s)
return True
except ValueError:
return False