上一篇展现的是表格的批量填写,遗留了一个环节没有加,那就是相片栏还没有相片,所以在这儿讲述下如何刺进图片
表格模板
依然是上一篇的模板,这相当所以循环里的一步操作,单独提取出来。
根本操作
简单刺进图片
wb_template = app.books.open('小学生信息表.xlsx')
ws_template = wb_template.sheets.active
ws_template.pictures.add(os.path.join(os.getcwd(),'th.jfif'))
直接刺进的话,图片的方位会是在左上角。这显然是不符合我们需求的
图片来自于搜索成果,假如是你的,感觉不合适,请直接联系我,我会在看到后尽快处理的
指定方位刺进图片
刺进图片的时分能够指定好图片的隶属单元格
photo_range = ws_template.range((2,6),(5,6))
ws_template.pictures.add(os.path.join(os.getcwd(), 'th.jfif'), left=photo_range.left,top=photo_range.top)
此时这张图片看上去就挂在了相片单元格的左上角
调整图片大小
photo_range = ws_template.range((2,6),(5,6))
row_height = photo_range.row_height
column_width = photo_range.column_width
print(row_height,column_width)
ws_template.pictures.add(os.path.join(os.getcwd(), 'th.jfif'), left=photo_range.left,top=photo_range.top,width=column_width,height=row_height)
经过设置width和height两个参数即可完成图形的缩放
你难道以为上面的会正常显示吗,其实是不会的,这个单元格的高度和宽度和图像的宽高是两种数据单位,需求额外转换。
在这儿我也发现row_height并不能范围区域的行高,来自官方文档的解说, Range – xlwings Documentation,当指定区域一样高的时分,会回来单个行高,但是假如不一样高,会回来一个None,所以这儿要乘以一个4,遇到不一样高的,主张运用循环读取出来,重新核算。
宽度的份额在我的电脑上经过调试,大约是5.63
photo_range = ws_template.range((2,6),(5,6))
row_height = photo_range.row_height*4
column_width = photo_range.column_width
print(row_height,column_width)
ws_template.pictures.add(os.path.join(os.getcwd(), 'th.jfif'), left=photo_range.left,top=photo_range.top,width=column_width*5.63,height=row_height)
得到的成果如下:
额外
在工作中也能够对图片进行保持份额。利用pillow库读取文件的尺寸,进行类似居中的操作。
photo_range = ws_template.range((2, 6), (5, 6))
row_height = photo_range.row_height * 4
column_width = photo_range.column_width
pic_width, pic_height = Image.open('th.jfif').size
# 份额
ratio = pic_width / pic_height
print(ratio)
# 图片的实践宽度
pic_table_width = ratio * row_height
# 核算左边的方位,即为鸿沟方位加上半个差
left = photo_range.left + (column_width * 5.63 - pic_table_width) / 2
ws_template.pictures.add(os.path.join(os.getcwd(), 'th.jfif'), left=left, top=photo_range.top,
width=pic_table_width, height=row_height)
完成作用
当然,这儿默认了图片是高大于宽的,能够根据ratio是否大于1来确认到底是调整宽度仍是高度。 在核算图片实践宽度时,这个已经是相当于像素值了,不需求额外的乘以列宽份额。