首页 > 解决方案 > 如何使用openpyxl更改图片大小

问题描述

那里。我想使用 openpyxl 更改图片的大小。宽度 = 11.21 厘米。高度 = 7.69 厘米。

或者我想更改与单元格相同的图片大小。

我的代码如下。它可以制作非常小的图片。你可以帮帮我吗?

from openpyxl import load_workbook
from openpyxl.drawing.image import Image

filename="1.xlsx"
wb = load_workbook(filename)
ws = wb.worksheets[0]
img = Image('13.5.jpg')
img.width = 11.21
img.height = 7.69
ws.add_image(img, 'B13')
wb.save('1.xlsx')
print("done")

标签: pythonopenpyxl

解决方案


为了向其他人澄清(keineahnung2345 有正确的帖子,我的只是补充),这是设置图像大小的方法:

img = openpyxl.drawing.image.Image('filelocation.png')
img.height = # insert image height in pixels as float or int (e.g. 305.5)
img.width= # insert image width in pixels as float or int (e.g. 405.8)
img.anchor = 'A1' # where you want image to be anchored/start from
sheet.add_image(img) # adding in the image

再次确保检查作为像素量乘数的 dpi。您可以通过单击 excel 中的图像并检查属性来检查图像大小,它应该为您提供以英寸或厘米为单位的大小。

对于使用英寸的任何人,这里有一个英寸到像素的转换器: https ://www.unitconverters.net/typography/inch-to-pixel-x.htm

厘米转换器可以在 keineahnung2345 的选定答案中找到。


推荐阅读