为什么我的 header 图片从我的模板中消失了?

Why does my header image disappear from my template?

我在Excel做了一个模板文档,除了header里面有我们部门的标志(下图),大部分都是空的。

然后我使用 openpyxl 将此模板文档读入 python 并用数据框填充它。但是,当我保存工作簿并打开 Excel 文档时,一切都完好无损,除了我的图像消失了。

如何确保我的徽标在报告中保持完整?我知道我不能将图像插入 openpyxl 中的 header,所以我希望通过将它包含在我的模板中(永远不要触及 header)它会保留下来,但它不是't。

代码在Python

from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows

wb = load_workbook('./template.xlsx')
ws = wb["Sheet1"]

for r in dataframe_to_rows(df, index=False, header=False):
    ws.append(r)

wb.save("{}".format(fn))

可惜openpyxl暂时不支持图片,看官方文档:https://openpyxl.readthedocs.io/en/stable/usage.html#read-an-existing-workbook

openpyxl does currently not read all possible items in an Excel file so images and charts will be lost from existing files if they are opened and saved with the same name.

因此当您打开模板文件时,图像不会被读取,因此不会保存在新文件中。 因此,您可能必须改用 xlsxwriter。