0

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()
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
  • Exact error message would be helpful – Maxim Kukhtenkov Feb 24 '23 at 22:58
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – moken Feb 26 '23 at 09:55
  • I have an excel file, which contains an image in the header, I want to change the values ​​in the file with openpyxl and make a copy. But during the file copy , the header image disappears, I can add a new one, but I wanted to know if there is a way to keep the initial image. there is no error message just a copy without image – Arnaud2020 D Feb 28 '23 at 07:21
  • May be related to this [Warning](https://openpyxl.readthedocs.io/en/stable/tutorial.html?highlight=shapes#loading-from-a-file) in Openpyxl related to shapes. Warning: openpyxl does currently not read all possible items in an Excel file so shapes will be lost from existing files if they are opened and saved with the same name. If you need to explore deeper you might need to raise an issue with the developers. – moken Mar 01 '23 at 09:03

1 Answers1

1

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