'Excel Content Error - fail to open file written with xlsx writer in Pandas 3.X

I have a dataframe that I write in excel with a python script. There are many times that excel will not open and I need to re-run the code. Once I do, it is ok 99% of the time. Haven't been able to understand what goes wrong.

Here is the excel error I get on opening the file:

"Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded. Replaced Part: /xl/worksheets/sheet1.xml part with XML error. The name in the end tag of the element must match the element type in the start tag. Line 2, column 110654881."

This XML file does not appear to have any style information associated with it. The document tree is shown below. error188320_01.xml Errors were detected in file 'C:\Users\Folder\filename.xlsx' Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded. Replaced Part: /xl/worksheets/sheet1.xml part with XML error. The name in the end tag of the element must match the element type in the start tag. Line 2, column 110654881.

My file has 100 columns and the error refers to column 110654881.

My code is:

    path = str(r"C:\Users\username\Folder/")     
    path_panel = path
    name_file = path_panel + "filename_"+ date + ".xlsx"
    
    writer = pd.ExcelWriter(str(name_file), engine="xlsxwriter", options= 
    'strings_to_urls': False , 'strings_to_formulas': False})
    df1.to_excel(writer, encoding="utf-8",sheet_name="sheet1",index=False)
    workbook = writer.book
    
    worksheet = writer.sheets["sheet1"] 
    
    for col_num, value in enumerate(df1.columns.values):
            worksheet.write(0, col_num, value, header_format)
    for idx, col in enumerate(df1): 
            series = df1[col]
            max_len = max((
                series.astype(str.encode("unicode")).map(len).max(),  
                len(str(series.name))
                )) + 1
            worksheet.set_column(idx, idx, max_len)    
    writer.close()    


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source