Home » excel » excel – Python function inputting variables into strings

excel – Python function inputting variables into strings

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have outputted a pandas df into an excel file using xlsxwriter. I’m trying to create a totals row at the top. To do so, I’m trying to create a function that dynamically populates the totals based off the column I choose.

Here is an example of what I’m intending to do:

worksheet.write_formula('G4', '=SUM(G4:G21)')
#G4 = Where total should be placed

I need this to be a function because the row counts can change (summation range should be dynamic), and I want there to be an easy way to apply this formula to various columns.

Therefore I’ve come up with the following:

def get_totals(column):
    start_row = '4' #row which the totals will be on
    row_count = str(tl_report.shape[0]) #number of rows in the table so I can sum up every row.  
    return (worksheet.write_formula(str(column+start_row),"'=SUM("+str(column+start_row)+":"+str(column+row_count)+")'") )


When running get_totals(“G”) it just results in 0. I’m suspecting it has to do with the STR operator that I had to apply because its adding single quotes to the formula, and therefore rendering it incorrectly.

However I cannot take the str operator out because I cannot concatenate INTs apparently?

Maybe I’m coding this all wrong, new to python, any help appreciated.

Thank you!

How to&Answers:

You could also do something like this:

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1,2,3,4], 'B': [5,6,7,8],
                    'C': [np.nan, np.nan, np.nan, np.nan]})

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False, startrow = 2)
workbook = writer.book
worksheet = writer.sheets['Sheet1']

def get_totals(start_row, sum_column, column1='A', column2='B'):
    for row in range(start_row,df.shape[0]+start_row):
        worksheet.write_formula(f'{sum_column}{row}', f'=SUM({column1}{row},{column2}{row})')

get_totals(4, 'C')

writer.save()

Output:

enter image description here

Answer:

In almost all cases XlsxWriter methods support two forms of notation to designate the position of cells: Row-column notation and A1 notation.

Row-column notation uses a zero based index for both row and column while A1 notation uses the standard Excel alphanumeric sequence of column letter and 1-based row. For example:

(6, 2)      # Row-column notation.
('C7')      # The same cell in A1 notation.

So for your case you could do the following and set the row-column values programatically (you may have to adjust by -1 to get zero indexing):

worksheet.write_formula(start_row, start_column, '=SUM(G4:G21)')

For the formula you could use of of XlsxWriter’s utility functions:

from xlsxwriter.utility import xl_range 

my_range = xl_range(3, 6, 20, 6)  # G4:G21