Search code examples
pythonexcelxlsxwriter

Applying xlsxwriter formula to entire column


I have tried this XLSXWriter Apply Formula Across Column With Dynamic Cell Reference and looking at the documentation, but I can't seem to figure out how to apply this to my code.

I have many formulas for new columns:

with xlsxwriter.Workbook('workbook.xlsx') as workbook:
    worksheet = workbook.add_worksheet() #Creates excel doc and sheet

    for row_num, data in enumerate(user_input):
        worksheet.write_row(row_num, 0, data)
        worksheet.write_formula('X3', '=W3/G3')
        worksheet.write_formula('Y3', '=(X3-K3)/K3')
        worksheet.write_formula('Z3', '=(X3-R3)/R3')
        worksheet.write_formula('AA3', '=X3/N3')
        worksheet.write_formula('AB3', '=(P3/Q3-1)')
        worksheet.write_formula('AC3', '=O3/N3')
        worksheet.write_formula('AD3', '=(R3-K3)/K3')
        worksheet.write_formula('AE3', '=(X3/P3-M3/1000)/(X3/P3)')
        worksheet.write_formula('AF3', '=(AA3-0.1)/0.1')
        worksheet.write_formula('AG3', '=M3*N3/1000')
        worksheet.write_formula('AH3', '=(R3-AG3)/AG3')

Currently, they are all using row 3 to make the calculations and adding the new columns into row 3. I want to write a loop that applies every single one of these formulas all the way down their columns beginning at row 2. There is not a specific amount of rows that will be added each time this is run, however if there has to be a range in order to create the loop I would do about 100 rows. Thanks in advance for any help.


Solution

  • Here is one way to do it using Python fstrings:

    import xlsxwriter
    
    # Sample data.
    user_input = [range(23)] * 5
    
    with xlsxwriter.Workbook('workbook.xlsx') as workbook:
        worksheet = workbook.add_worksheet()
    
        for row_num, data in enumerate(user_input, 3):
            worksheet.write_row(row_num - 1, 0, data)
            worksheet.write_formula(row_num - 1, 23, f'=W{row_num}/G{row_num}')
            worksheet.write_formula(row_num - 1, 24, f'=(X{row_num}-K{row_num})/K{row_num}')
            worksheet.write_formula(row_num - 1, 25, f'=(X{row_num}-R{row_num})/R{row_num}')
            worksheet.write_formula(row_num - 1, 26, f'=X{row_num}/N{row_num}')
            # ...
    

    Output:

    enter image description here