I use the following class that I wrote to try and dynamically create a single Excel file with multiple worksheets that have a printed data block and a column chart on each worksheet.
The interaction with the code (see below) should function where you run the book:
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 create a book:
test.produce()
Input data frames have headers. The first column is the textual categories, the subsequent columns (of different numbers) are the data in decimal places, which should be displayed as a percentage.
: , , , " ", , , . , , DO , , , .
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)
for n in range(0, df_width):
col_n = dataframe[col_names[n]].tolist()
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)
worksheet.write_column(self.letters[n] + '1', col_as_lists[n])
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