无法使用 openpyxl 或 win32com 将图像导入 Excel 标题

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

我需要以自动方式将图像文件放入 Excel 标题中;我不相信这在 openpyxl 中是可能的,但我认为这在 win32com 中可能是可行的,尽管我无法让它工作。有谁知道如何做到这一点?我找到了一个 Excel 宏,可以在 Excel 中成功完成此操作:

Sub InsertPicture
 With ActiveSheet.PageSetup.LeftHeaderPicture
  .FileName = "C:/Users/bharris/Desktop/my_image_file.png"
  .Height = 45
  .Width = 30
  .CropTop = -30
 End With
 ActiveSheet.PageSetup.LeftHeader = "&;G"

所以我尝试使用 win32com 从 python 中实现:

excel = DispatchEx('Excel.Application')
excel.Visible = True
wb=excel.Workbooks.Open(my_excel_file.xlsx')
ws = wb.Sheets(1)
ws.PageSetup.LeftHeaderPicture.FileName ="my_image_file.png"
ws.PageSetup.LeftHeader = "&;G"
wb.SaveAs('my_excel_file.xlsx')
wb.Close(True, 'my_excel_file.xlsx')
excel.Application.Quit()

但它给了我:

raise AttributeError("Property '%s.%s' can not be set." % (self._username_, attr))
AttributeError: Property '<unknown>.FileName' can not be set.

所以看起来 FileName 不是 win32com 中的属性,就像 Excel 中的 VBA 中的属性一样。我尝试了一些不同的组合,但似乎没有任何效果。如果有人知道如何使用任何类型的 openpyxl 或 win32com 代码或任何其他代码(尽管它必须能够编辑现有电子表格,而不仅仅是编写像 xlsxwriter 这样的新电子表格),那么非常感谢您的帮助!

附注我已经找到了几种有关如何将图像插入单元格的解决方案,但这个问题是专门用于插入标题的。

非常感谢, 罗伯特

python excel header openpyxl win32com
1个回答
0
投票

我知道这个问题很旧,但认为应该关闭它:

制作: ws.PageSetup.LeftHeaderPicture.FileName =“my_image_file.png”

ws.PageSetup.LeftHeader = "&;G"

进入: ws.PageSetup.LeftHeaderPicture.Filename =“my_image_file.png”

ws.PageSetup.LeftHeader = "&G"

© www.soinside.com 2019 - 2024. All rights reserved.