【问题标题】:Pictures not attached in file图片未附在文件中
【发布时间】:2013-07-06 06:57:11
【问题描述】:

我正在使用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 的解决方法?

【问题讨论】:

    标签: python excel-2010 image


    【解决方案1】:

    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 来调整图像的大小。

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 2016-01-17
      • 2017-10-05
      • 2017-05-02
      相关资源
      最近更新 更多