Why are my Excel headers shifted to the right 1 cell?

I’m using Python 3.11 on Windows 10 along with Pandas. Here are my module versions:

* Pandas v2.2.2
* xlsxwriter v3.2.0

I’m reading a spreadsheet file to grab the headers. When I extract the headers with df.columns.tolist() the headers are correct. When I write the output spreadsheet my first header “County” is repeated like this:

County County  Specialty  Firstname  Lastname...

I’m writing the spreadsheet like this, headers from the spreadsheet I read are in options.outputhdrs.

    sheetname = "Sheet1"
    df = pandas.DataFrame(outarr, columns=options.outputhdrs) # import pandas
    writer = pandas.ExcelWriter(options.outfilename, engine='xlsxwriter')
    df.to_excel(writer, sheet_name=sheetname, index=False)
    workbook = writer.book # Get workbook object.
    worksheet = writer.sheets[sheetname]
    hdrformat = workbook.add_format({'bold':True,
    'text_wrap':True, 'valign':'top', 'align':'left'})
    
    writer.sheets[sheetname].set_column(1, 15, 12) # Set column width here.
    worksheet.set_column(5,5,12) # Format: Begcol, Endcol, Width.
    worksheet.set_landscape() # It works!
    worksheet.set_zoom(75) # Set view zoom to 75%.
    worksheet.set_margins(left=0.7, right=0.7, top=0.75, bottom=0.75) # Set left margins in inches
    worksheet.freeze_panes(0,0) # Format: (row, col) both required.
    worksheet.set_header('&F - &A')
    worksheet.set_footer('&D  &T') # Date and time    
    # Format the header row only.
    for col_num, value in enumerate(df.columns.values):
        worksheet.write(0, col_num + 1, value, hdrformat)
    
    writer.close() # Saves the file.
    print(f"{procname} Wrote file {options.outfilename}")

If the first “County” was removed and all headers shifted left one cell it would be correct.

How do I fix this?

Thank you!

I suspect you shouldn’t have col_num + 1 here, it should just be col_num?

Well that was it. I thought that statement only applied a header format but I guess I was wrong.

Thanks!