Python xlwings插入Excel图片的实现方法
作者:XerCis 发布时间:2023-11-23 05:53:18
测试图片
一、相对路径(报错)
使用相对路径插入会报错(确认路径正确无误)
import xlwings as xw
wb = xw.Book()
sht = wb.sheets['Sheet1']
sht.pictures.add('1.jpg') # 使用相对路径会报错
wb.save('test.xlsx')
wb.close()
File "<COMObject <unknown>>", line 5, in AddPicture
pywintypes.com_error: (-2147352567, '发生意外。', (0, None, '未找到指定文件。', None, 0, -2146827284), None)
二、绝对路径
改为绝对路径即可成功插入
import os
import xlwings as xw
wb = xw.Book()
sht = wb.sheets['Sheet1']
# sht.pictures.add('1.jpg') # 使用相对路径会报错
sht.pictures.add(os.path.join(os.getcwd(), '1.jpg'))
wb.save('test.xlsx')
wb.close()
三、指定位置和大小
函数原型add(image, link_to_file=False, save_with_document=True, left=0, top=0, width=None, height=None, name=None, update=False)
import os
import xlwings as xw
wb = xw.Book()
sht = wb.sheets['Sheet1']
fileName = os.path.join(os.getcwd(), '1.jpg')
sht.pictures.add(fileName, left=sht.range('B5').left, top=sht.range('B5').top, width=100, height=100)
wb.save('test.xlsx')
wb.close()
指定图片位置为B5
单元格的左上角,图片像素为100×100
四、居中插入
新建Excel文件test.xlsx
,设置列宽20行高100
import os
import xlwings as xw
wb = xw.Book('test.xlsx') # 打开已存在的Excel文件
sht = wb.sheets['Sheet1']
rng = sht.range('B2') # 目标单元格
fileName = os.path.join(os.getcwd(), '1.jpg')
width, height = 80, 80 # 指定图片大小
left = rng.left + (rng.width - width) / 2 # 居中
top = rng.top + (rng.height - height) / 2
sht.pictures.add(fileName, left=left, top=top, width=width, height=height)
wb.save()
wb.close()
智能居中插入
1.jpg
宽 × 高 = 188 × 282
2.jpg
宽 × 高 = 200 × 153
import os
import xlwings as xw
from PIL import Image
def add_center(sht, target, filePath, match=False, width=None, height=None, column_width=None, row_height=None):
'''Excel智能居中插入图片
优先级:match > width & height > column_width & row_height
建议使用column_width或row_height,定义单元格最大宽或高
:param sht: 工作表
:param target: 目标单元格,字符串,如'A1'
:param filePath: 图片绝对路径
:param width: 图片宽度
:param height: 图片高度
:param column_width: 单元格最大宽度,默认100像素,0 <= column_width <= 1557.285
:param row_height: 单元格最大高度,默认75像素,0 <= row_height <= 409.5
:param match: 绝对匹配原图宽高,最大宽度1557.285,最大高度409.5
'''
unit_width = 6.107 # Excel默认列宽与像素的比
rng = sht.range(target) # 目标单元格
name = os.path.basename(filePath) # 文件名
_width, _height = Image.open(filePath).size # 原图片宽高
NOT_SET = True # 未设置单元格宽高
# match
if match: # 绝对匹配图像
width, height = _width, _height
else: # 不绝对匹配图像
# width & height
if width or height:
if not height: # 指定了宽,等比计算高
height = width / _width * _height
if not width: # 指定了高,等比计算宽
width = height / _height * _width
else:
# column_width & row_height
if column_width and row_height: # 同时指定单元格最大宽高
width = row_height / _height * _width # 根据单元格最大高度假设宽
height = column_width / _width * _height # 根据单元格最大宽度假设高
area_width = column_width * height # 假设宽优先的面积
area_height = row_height * width # 假设高优先的面积
if area_width > area_height:
width = column_width
else:
height = row_height
elif not column_width and not row_height: # 均无指定单元格最大宽高
column_width = 100
row_height = 75
rng.column_width = column_width / unit_width # 更新当前宽度
rng.row_height = row_height # 更新当前高度
NOT_SET = False
width = row_height / _height * _width # 根据单元格最大高度假设宽
height = column_width / _width * _height # 根据单元格最大宽度假设高
area_width = column_width * height # 假设宽优先的面积
area_height = row_height * width # 假设高优先的面积
if area_width > area_height:
height = row_height
else:
width = column_width
else:
width = row_height / _height * _width if row_height else column_width # 仅设了单元格最大宽度
height = column_width / _width * _height if column_width else row_height # 仅设了单元格最大高度
assert 0 <= width / unit_width <= 255
assert 0 <= height <= 409.5
if NOT_SET:
rng.column_width = width / unit_width # 更新当前宽度
rng.row_height = height # 更新当前高度
left = rng.left + (rng.width - width) / 2 # 居中
top = rng.top + (rng.height - height) / 2
try:
sht.pictures.add(filePath, left=left, top=top, width=width, height=height, scale=None, name=name)
except Exception: # 已有同名图片,采用默认命名
pass
if __name__ == '__main__':
wb = xw.Book()
sht = wb.sheets['Sheet1']
filePath = os.path.join(os.getcwd(), '1.jpg')
filePath2 = os.path.join(os.getcwd(), '2.jpg')
add_center(sht, 'A1', filePath) # 默认值
add_center(sht, 'B2', filePath2) # 默认值
add_center(sht, 'C3', filePath, match=True) # 绝对匹配图片宽高
add_center(sht, 'D4', filePath, width=100) # 图片宽度为100像素
add_center(sht, 'E5', filePath, height=100) # 图片高度为100像素
add_center(sht, 'F6', filePath, width=100, height=100) # 图片高度为100像素
add_center(sht, 'G7', filePath, column_width=100) # 单元格最大宽度为100像素
add_center(sht, 'H8', filePath, row_height=100) # 单元格最大宽度为100像素
add_center(sht, 'I9', filePath, column_width=100, row_height=100) # 单元格最大高度或宽度为100像素
效果
unit_width = 6.107 # Excel默认列宽与像素的比
这个值估计与不同机器、分辨率有关,在5.7-6.2之间
遇到的坑
报错 pywintypes.com_error: (-2147352567, '发生意外。', (0, None, '未找到指定文件。', None, 0, -2146827284), None)
对路径使用os.path.abspath()
参考文献
xlwings dev documentation
报错pywintypes.com_error: (-2147352567, ‘发生意外。‘, (0, None, ‘未找到指定文件。‘, None, 0, -2146827284), None)
来源:https://blog.csdn.net/lly1122334/article/details/100160206
猜你喜欢
- 简易网页搜集器前面我们已经学会了简单爬取浏览器页面的爬虫。但事实上我们的需求当然不是爬取搜狗首页或是B站首页这么简单,再不济,我们都希望可以
- 文章主要描述的是SQL Server到DB2连接服务器的正确实现过程,以及对其在实际操作中所要用到的实际操作环境的描述,以下就是对SQL S
- 转自微信公众号: Python之禅1.日志简介说到日志,无论是写框架代码还是业务代码,都离不开日志的记录,他能给我们定位问题带来极
- 看到Django和layim实现websocketde资料很少,自己就琢磨了下,顺便搭建出来了。自己要去找闲心大神授权呀。先来看图这是初次搭
- 最近在调代码,碰到幂函数、指数函数,总是提示ValueError: math domain errorValueError: negativ
- Seaborn - 绘制多标签的混淆矩阵、召回、精准、F1导入seaborn\matplotlib\scipy\sklearn等包:impo
- 网站设计似乎朝着越来越复杂的方向发展。这部分源于显示器的逐步增大,随着宽屏显示器的增多,更有加剧网站页面复杂程度的趋势。但是我接触网站设计近
- 本文实例讲述了Python使用django获取用户IP地址的方法。分享给大家供大家参考。具体如下:函数实现:def get_client_i
- 信息安全的核心就是数据库的安全,也就是说数据库加密是信息安全的核心问题。数据库数据的安全问题越来越受到重视,数据库加密技术的应用极大的解决了
- 前面的python3入门系列基本上也对python入了门,从这章起就开始介绍下python的爬虫教程,拿出来给大家分享;爬虫说的简单,就是去
- 有时候,我们需要将文本转换为图片,比如发长微博,或者不想让人轻易复制我们的文本内容等时候。目前类似的工具已经有了不少,不过我觉得用得都不是很
- 一,封装封装是面向对象编程思想的重要特征之一。(一)什么是封装封装是一个抽象对象的过程,它容纳了对象的属性和行为实现细节,并以此对外提供公共
- 本文主要通过对海康摄像头进行抓包,模拟发送了udp包,并抓取摄像头返回的数据包,解析并提取相关信息。通过抓包发现,海康摄像头发送、接收数据使
- 一、计数排序计数排序(Counting sort)是一种稳定的排序算法算法的步骤如下:找出待排序的数组中最大和最小的元素统计数组中每个值为i
- 在深度学习中,如果我们想获得某一个层上的feature map,就像下面的图这样,怎么做呢?我们的代码是使用keras写的VGG16网络,网
- ThinkPHP的分组功能是广为开发者使用的一个具有很大实用价值的功能,该功能可以解决中大型项目情况中MVC分层文件过多导致不易管理的问题。
- 毫无疑问,Google是当今世界上最成功的互联网公司之一,但是Google也曾推出过一些失败的实验品。还记得Google Accelerat
- 1、开始->运行,输入SERVICES.MSC到服务里,停止所有Oracle服务; 2、开始->程序->Oracle - OraHome81
- 栅格就是你对页面版式的规划你日常所见的许多页面都有栅格存在。你可能注意不到,但它确实存在,并且支撑着设计内容,建立整体的架构,引导着页面的元
- 今天在修改 淘宝 宝贝详情页面的时候,发现页面在 Firefox 下遇到这样一个问题:链接用图片做背景,text-indent:-9999p