1

我正在使用python win32驱动excel 2010。我想将图片插入某些单元格

import win32com.client as win32
from win32com.client import constants as constants

excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True

wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1')
ws.Name = 'PicDemo' ## rename worksheet

## select the active sheet
excel.Sheets('PicDemo').Select()
ws = excel.ActiveSheet
ws.Cells(9,9).Select()

## insert a png pic into this cell
ws.Pictures().Insert(pic file path)

我可以在我的电脑上看到插入的图片,但是当我将 excel 发送给我的朋友时,他们看不到图片,而是带有“无效链接”的红叉。

我在网上搜索,很多人抱怨 excel 2010 中的这个故障。我只希望绝对保存图片而没有任何依赖链接。

是否有 python win32 解决方法?

4

1 回答 1

0

Microsoft 更改了 Excel 2010 和 2013 中的行为。试试这个:

xlApp = win32.Dispatch(r'Excel.Application')
xlBook = xlApp.Workbooks.Open(filename)
xlSheet = xlBook.Sheets(sheet_name)
rng = xlSheet.Range("B2:F8")
height = rng.Offset(rng.Rows.Count, 0).Top - rng.Top
width = rng.Offset(0, rng.Columns.Count).Left - rng.Left
xlSheet.Shapes.AddPicture(image_file_name, False, True, rng.Left, rng.Top, height, width)

AddPicture具有将图像与文档一起保存的选项。

高度和宽度是必需的。在上面的代码中,我使用 Range 来调整图像的大小。

于 2015-05-01T16:27:39.967 回答