from openpyxl.drawing.image import Image是用于在 Excel 工作表中插入图片的导入语句但该用法已过时且不推荐。自openpyxl2.5 版本起Image类已从openpyxl.drawing.image移至openpyxl.drawing.spreadsheet_drawing内部模块而用户应使用openpyxl.worksheet._images.Image或更准确地说直接从openpyxl.drawing.image导入Image在新版中虽仍可工作但存在兼容性风险。✅ 正确、稳定、官方推荐的用法是fromopenpyxlimportWorkbookfromopenpyxl.drawing.imageimportImage# ✅ 当前版本如 3.1.x仍支持但需注意路径# 注意Image 类用于加载图片如 PNG/JPEG然后添加到 worksheet示例fromopenpyxlimportWorkbookfromopenpyxl.drawing.imageimportImage wbWorkbook()wswb.active# 加载图片路径需存在imgImage(example.png)img.anchorA1# 设置锚定单元格左上角ws.add_image(img)# ⚠️ 注意不是 ws.add_image()而是 ws._images.append(img)错# ✅ 正确添加方式openpyxl ≥ 2.6ws.add_image(img,A1)# 第二个参数为锚定单元格自动定位wb.save(with_image.xlsx)⚠️ 注意事项图片文件必须存在且格式为.png,.jpeg,.jpg.bmp不支持add_image()的第二个参数是目标单元格字符串如B2会自动计算偏移openpyxl不支持向单元格内嵌入图片即不能像 Excel 手动“置于单元格内”图片是浮动对象anchored若报错AttributeError: Worksheet object has no attribute add_image说明版本过低2.6请升级pip install --upgrade openpyxl。在openpyxl中无法直接通过.width/.height属性设置图片尺寸这些属性不存在但可以通过修改图片对象的width和height属性单位为像素来调整显示大小。⚠️ 注意该调整仅影响 Excel 中的渲染尺寸不改变原始图像分辨率且需在调用ws.add_image(img, anchor)之前设置。✅ 正确做法openpyxl ≥ 2.6fromopenpyxlimportWorkbookfromopenpyxl.drawing.imageimportImage wbWorkbook()wswb.active imgImage(logo.png)# ✅ 调整图片宽高单位像素img.width200# 宽度设为 200 像素img.height150# 高度设为 150 像素# ⚠️ 注意若只设 width 或 heightopenpyxl 不自动等比缩放即不保持宽高比# 如需等比缩放需手动计算# original_w, original_h img.width, img.height# scale 0.5# img.width int(original_w * scale)# img.height int(original_h * scale)ws.add_image(img,A1)wb.save(resized_image.xlsx) 补充说明img.width/img.height是openpyxl.drawing.image.Image对象的可写属性底层映射到 Excel 的xdr:ext尺寸若未显式设置openpyxl默认使用图片原始像素尺寸设置后Excel 中图片将按指定像素值渲染受 Excel 缩放和 DPI 影响实际显示可能略有差异❌ 不支持设置厘米/英寸等绝对单位——需自行按 96 DPI 换算1 英寸 ≈ 96 像素若需精确控制如 5cm × 3cm可换算width_px int(5 * 96 / 2.54) ≈ 189height_px int(3 * 96 / 2.54) ≈ 113。