Python - Formatting excel sheet too slow (row by row)

I am trying to format an excel sheet using python using the function like this,

def highlight_myrow_cells(sheetnumber, Sheetname ,dataFrame):
    Pre_Out_df_ncol = dataFrame.shape[1]
    RequiredCol_let = colnum_num_string(Pre_Out_df_ncol)

    #identifying the rows that needs to be highlighted
    arr = (dataFrame.select_dtypes(include=[bool])).eq(False).any(axis=1).values
    ReqRows = np.arange(1, len(dataFrame) + 1)[arr].tolist()
    #The ReqRows are a list of values something like [1,2,3,5,6,8,10]
    print("Highlighting the Sheet " + Sheetname + " in the output workbook")

    # Program is too slow over here---
    for i in range(len(ReqRows)):
        j = ReqRows[i] + 1
        xlwb1.sheets(sheetnumber).Range('A' + str(j) + ":" + RequiredCol_let + str(j)).Interior.ColorIndex = 6
    xlwb1.sheets(sheetnumber).Columns.AutoFit()

    for i in range(1, Emergency_df.shape[1]):
        j = i - 1
        RequiredCol_let = colnum_num_string(i)
        Required_Column_Name = (Emergency_df.columns[j])
        DateChecker1 = contains_word(Required_Column_Name, "Date", "of Death", "Day of Work")
        ResultChecker = Required_Column_Name.startswith("Result")
        if ResultChecker == False:
            if (DateChecker1 == True):
                xlwb1.sheets(sheetnumber).Range(Required_Column_Name + ":" + Required_Column_Name).NumberFormat = "m/d/yyyy"

The program is too slow while highlighting the rows based on logics,

From what I understand from excel is - the speed is quiet good if you highlight using a range of rows, rather than to use one row after another row.

I am not looking to do this with an external library like stylewriter etc.,

Upvotes: 0

Views: 63

Answers (1)

Reedinationer
Reedinationer

Reputation: 5774

Since you can't use threading, I would just cut down the time needed to execute each loop. The methods I know of would look something like:

    ReqRows += 1
    for i in range(len(ReqRows)):
        xlwb1.sheets(sheetnumber).Range('A{0}:{1}{0}'.format(i, RequiredCol_let)).Interior.ColorIndex = 6
    xlwb1.sheets(sheetnumber).Columns.AutoFit()

This should speed up your loop (albeit probably not nearly as much as threading). Hope this helps solve your problem!

Upvotes: 1

Related Questions