我们在表格中插入图片位置和大小能随单元格而变化,百度搜索无效文章多如牛毛,终于发现一个好的方法与君共勉
import io
import openpyxl
from openpyxl import Workbook
from openpyxl.drawing.image import Image as OpenpyxlImage
from openpyxl.drawing.spreadsheet_drawing import AnchorMarker, TwoCellAnchor
from openpyxl.utils import get_column_interval
def insert_image_into_cell(worksheet, cell_reference, image_path):
"""
在指定的单元格中插入图片,并尝试调整图片大小以匹配单元格。
:param worksheet: openpyxl 的工作表对象
:param cell_reference: 单元格引用,例如 'A1'
:param image_path: 图片文件的路径
"""
worksheet[cell_reference].value = "fsdfasdf"
# 插入图片到工作表并指定其左上角位置
img = OpenpyxlImage(image_path)
#设置图片高宽
img.height, img.width = (180, 180)
col, row = openpyxl.utils.cell.coordinate_from_string(cell_reference)
# 设置列宽自行设置(注意:这里使用的是默认的1字符宽度和1磅高度作为起始值)
worksheet.column_dimensions[col].width = 180
worksheet.row_dimensions[row].height = 180
# 以下为自适应重要代码
# AnchorMarker(列,微调,行,微调)
# 第一和第三个数要一致从0开始表示单元格最左侧,第二个数为图片距离单元格左侧偏移,第四个数为图片距离单元格上方偏移
_from = AnchorMarker(0, 0, 0, 0)
# 第一和第三个数要一致从1开始表示单元格最右侧,第二个数为图片距离单元格右侧偏移,第四个数为图片距离单元格下方偏移
to = AnchorMarker(2, 0, 2, -200000) # 2表示B列的右侧
img.anchor = TwoCellAnchor("twoCell", _from, to)
worksheet.add_image(img)
# 示例用法
wb = Workbook()
ws = wb.active
# 插入图片到单元格A1
insert_image_into_cell(ws, 'A1', 'baidu_0002.jpg')
# 保存工作簿
wb.save('example_with_image.xlsx')