网了查了各种方法都不成功,各种失败方法就不示例了。

最标准的代码,应该成功的,试了还是不成功,都是图片被压缩成了一个小点。网上查询还有说,在 openpyxl 3.1.3 版本中,Excel 导出图片锚点定位偏差是有BUG的。以下示例标准代码也不行

img_path = os.path.join(settings.BASE_DIR, file_name)  # 获取第一个图片路径及名称
img = Image(img_path)
max_size = 120
# 保持原图片比例,最大边是120
ratio = min(max_size / img.width, max_size / img.height)
new_width = img.width * ratio
new_height = img.height * ratio
# 转换为EMU
img.width = pixels_to_EMU(new_width)
img.height = pixels_to_EMU(new_height)

# 单位转换:字符/磅 → 像素 (经验公式)
cell_width_px = pixels_to_EMU(sheet.column_dimensions['E'].width * 7)  # 1字符 ≈ 7像素
cell_height_px = pixels_to_EMU(sheet.row_dimensions[row_num].height * 1.33)  # 1磅 ≈ 1.33px像素

# 计算居中偏移量(EMU)
x_offset_emu = (cell_width_px - img.width) / 2
y_offset_emu = (cell_height_px - img.height) / 2

# 创建定位锚点
anchor = AnchorMarker(
    col=4,  # E列
    row=row_num - 1,  # 第5行
    colOff=x_offset_emu,  # 1mm  因为1cm = 36万EMU       #colOff=360000
    rowOff=y_offset_emu,
)
# 绑定到OneCellAnchor
img.anchor = OneCellAnchor(_from=anchor)
sheet.a

最后添加使用 XDRPositiveSize2D 测试成功。

img_path = os.path.join(settings.BASE_DIR, file_name)  # 获取第一个图
img = Image(img_path)
max_size = 120
# 保持原图片比例,最大边是120
ratio = min(max_size / img.width, max_size / img.height)
new_width = img.width * ratio
new_height = img.height * ratio
# 转换为EMU
img.width = pixels_to_EMU(new_width)
img.height = pixels_to_EMU(new_height)

# 计算单元格尺寸(EMU单位)
cell_width_emu = pixels_to_EMU(sheet.column_dimensions['E'].width * 7)
cell_height_emu = pixels_to_EMU(sheet.row_dimensions[row_num].height * 1.33)

# 计算居中偏移量(EMU)
x_offset_emu = (cell_width_emu - img.width) / 2
y_offset_emu = (cell_height_emu - img.height) / 2

# 创建定位锚点           # 1cm = 36万EMU
anchor = AnchorMarker(
    col=4,  # E列
    row=row_num - 1,
    colOff=int(x_offset_emu),  # 必须为整数EMU
    rowOff=int(y_offset_emu)
)
# 创建尺寸对象
size = XDRPositiveSize2D(img.width, img.height)
# 绑定到OneCellAnchor
img.anchor = OneCellAnchor(_from=anchor, ext=size)
sheet.add_image(img)

这个必须记录保存一下,就这个场景浪费了好几天。终于实现锚点偏移了。高兴一下!

我想应该有很多同志应该也有吧!

更多推荐