Search code examples
pythonexcelheaderopenpyxlfooter

openpyxl save an existing header/footer


I am trying to open an excel file that contains headers and footers and save them to a new file but it does not work, I can create some, but not save those already existing

source/destination file

from openpyxl import load_workbook
def modif_xlsx():
        wb = load_workbook("test.xlsx")
        ws = wb['Feuil1']
        wb.save("test2.xlsx")
modif_xlsx()

Solution

  • exact, the images are lost .... 1 solution is to use win32com .

    For people who have the same problem, here is an example

    import pythoncom
    from win32com import client
    
    print(" ===== excel_to_pdf ===== ")
    try:
        # Initialisation de l'utilisation des objets COM sur le thread actuel
        pythoncom.CoInitialize()
    
        # Lance l'application excel
        excel = client.Dispatch("Excel.Application")
    
        # Ouvre le fichier xslx et la feuille
        fichier = "/path/fichier_xlsx"
        wb = excel.Workbooks.Open(Filename=fichier)
        ws = wb.Worksheets[feuille]
    
        # Ajout du header
        ws.PageSetup.RightHeaderPicture.Filename = "/path/image.jpg"
        ws.PageSetup.RightHeader = '&G'
    
        # Ajout du footer
        ws.PageSetup.LeftFooterPicture.Filename = "/path/image.jpg"
        ws.PageSetup.LeftFooter = '&G'
    
        try:
            # Supprime le fichier deja existant
            os.remove(os.path.join(url, fichier_pdf))
        except:pass
    
        # Enregistre le fichier en pdf
        #wb.SaveAs(os.path.join(url, fichier_xlsx),FileFormat=57)
        ws.ExportAsFixedFormat(0, os.path.join(url, fichier_pdf))
    
        # Fermeture d'excel
        wb.Close(False)
        del(wb)
        excel.Workbooks.Close()
        excel.Application.Quit()
        del(excel)
        return "pdf ok"
    except: raise