Dynamically produced XLSXWriter charts in python -

2019-05-05 17:48发布

问题:

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

回答1:

Your example invocations:

test.add_chart(df, 'Df Title', 1)
test.add_chart(df2, 'Df2 Title', 1)

suggest that you sometimes had spaces in the names. This results in broken references when you try things like

'name': '=' + tab_name +'!$' + self.letters[n] + '$1',

which would evaluate to

'name': '=Df Title!$A$1',

(when tab_name equals 'Df Title' and n equals 0), for example.

You should still be able to have sheet references with spaces, but enclosed in single-quotes, like

'name': "='Df Title'!$A$1",

so a more robust way to code would be

'name': "='" + tab_name +"'!$" + self.letters[n] + '$1',

I'm a little surprised that the charts would work at all with the broken sheet references, but I haven't actually tested charts myself, just plain cell formulas that involve sheet names.



回答2:

@John Y is correct that you aren't quoting the worksheet names correctly in chart range references.

You could avoid this issue, and the hand-rolled conversion from numbers to cell references, by using the chart list syntax rather than the string syntax:

chart.add_series({
    'name':       ['Sheet1', 0, col],
    'categories': ['Sheet1', 1, 0,   max_row, 0],
    'values':     ['Sheet1', 1, col, max_row, col],
})

The snippet is from this example in the XlsxWriter docs.

This applies to a few other places in your code as well. As a general rule in XlsxWriter you can use row-column syntax (almost) anywhere you would use A1 syntax: Working with Cell Notation.