openpyxl 保存现有页眉/页脚

问题描述 投票:0回答:1

我正在尝试打开一个包含页眉和页脚的 Excel 文件并将它们保存到一个新文件中 但它不起作用,我可以创建一些,但不能保存那些已经存在的

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()
python excel header openpyxl footer
1个回答
0
投票

确切地说,图像丢失了....第一个解决方案是使用 win32com .

遇到同样问题的人,这里有一个例子

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
© www.soinside.com 2019 - 2024. All rights reserved.