Dynamically created XLSXWriter diagrams in python - no links

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)    

    # 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
+4
2

:

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

, . , ,

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

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

( tab_name 'Df Title' n 0), .

, ,

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

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

, , , , .

+3

@John Y , .

, , :

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

XlsxWriter.

. , XlsxWriter row-column () , A1: .

+3

Source: https://habr.com/ru/post/1621521/


All Articles