Search code examples
pythonexceldataframeexporttarget

Python-Multiple header on dataframe


I have a dataframe which I export to excel file:

import pandas as pd    
Archivo_Descargado =r'C:\Users\Downloads\\'
FD_File="Prueba.xlsx" 
FD_Descarga= pd.read_excel(f'{Archivo_Descargado}{FD_File}')
full_path = f'{Archivo_Descargado}Aging.xlsx'
writer = pd.ExcelWriter(full_path, engine='xlsxwriter')
FD_Descarga.to_excel(writer, sheet_name='Aging', index=False)
workbook = writer.book
writer.save()

Example data:

Collector % 0-3 days %4-10 days %11-20 days
Juan 60 25 15
Maria 55 25 20

But I need to add a 2nd header and export to excel, called target above the first header

| Target | 70% | 30% | 0% |

Collector % 0-3 days %4-10 days %11-20 days
Juan 60 25 15
Maria 55 25 20

Any idea?

Regards


Solution

  • A not elegant approach would be to add this to the top:

    import openpyxl
    

    and add the following after your code:

    wb = openpyxl.load_workbook(full_path)
    ws = wb['Aging']
    ws.insert_rows(1)
    ws['A1'] = 'Target'
    ws['B1'] = '70%'
    ws['C1'] = '30%'
    ws['D1'] = '0%'
    wb.save(full_path)
    

    This is just inserting the line after the fact. I'm sure someone more savvy will have a better solution. It sounds like the additional row is unrelated to your DateFrame, so there is something to be said for applying a header after the fact.

    Target 70% 30% 0%
    Collector % 0-3 days %4-10 days %11-20 days
    Juan 60 25 15
    Maria 55 25 20