Python xlwings插入Excel图片的实现方法


Posted in Python onFebruary 26, 2021

测试图片

Python xlwings插入Excel图片的实现方法

一、相对路径(报错)

使用相对路径插入会报错(确认路径正确无误)

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()

Python xlwings插入Excel图片的实现方法

三、指定位置和大小

函数原型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

Python xlwings插入Excel图片的实现方法

四、居中插入

新建Excel文件test.xlsx,设置列宽20行高100

Python xlwings插入Excel图片的实现方法

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()

Python xlwings插入Excel图片的实现方法

智能居中插入

1.jpg

宽 × 高 = 188 × 282

Python xlwings插入Excel图片的实现方法

2.jpg

宽 × 高 = 200 × 153

Python xlwings插入Excel图片的实现方法

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像素

效果

Python xlwings插入Excel图片的实现方法

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)

到此这篇关于Python xlwings插入Excel图片的实现方法的文章就介绍到这了,更多相关Python xlwings插入图片内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
你应该知道的python列表去重方法
Jan 17 Python
深入探究Django中的Session与Cookie
Jul 30 Python
python机器学习理论与实战(二)决策树
Jan 19 Python
Python动态导入模块的方法实例分析
Jun 28 Python
详解python的sorted函数对字典按key排序和按value排序
Aug 10 Python
Python正则表达式和re库知识点总结
Feb 11 Python
Python Flask 搭建微信小程序后台详解
May 06 Python
pandas条件组合筛选和按范围筛选的示例代码
Aug 26 Python
Python3 mmap内存映射文件示例解析
Mar 23 Python
pytorch 计算ConvTranspose1d输出特征大小方式
Jun 23 Python
详解使用Python写一个向数据库填充数据的小工具(推荐)
Sep 11 Python
python代码实现猜拳小游戏
Nov 30 Python
基于tensorflow __init__、build 和call的使用小结
Feb 26 #Python
python实现MySQL指定表增量同步数据到clickhouse的脚本
Feb 26 #Python
详解python的xlwings库读写excel操作总结
Feb 26 #Python
pytorch 中forward 的用法与解释说明
Feb 26 #Python
浅谈Python xlwings 读取Excel文件的正确姿势
Feb 26 #Python
pycharm Tab键设置成4个空格的操作
Feb 26 #Python
解决pycharm 格式报错tabs和space不一致问题
Feb 26 #Python
You might like
cakephp打印sql语句的方法
2015/02/13 PHP
php将字符串全部转换成大写或者小写的方法
2015/03/17 PHP
ThinkPHP和UCenter接口冲突的解决方法
2016/07/25 PHP
深入理解PHP+Mysql分布式事务与解决方案
2020/12/03 PHP
多广告投放代码 推荐
2006/11/13 Javascript
基于jquery实现的上传图片及图片大小验证、图片预览效果代码
2011/04/12 Javascript
日期处理的js库(迷你版)--自建js库总结
2011/11/21 Javascript
JavaScript使用循环和分割来替换和删除元素实例
2014/10/13 Javascript
通过隐藏iframe实现无刷新上传文件操作
2016/03/16 Javascript
onmouseover事件和onmouseout事件全面理解
2016/08/15 Javascript
轻松实现js选项卡切换效果
2016/09/24 Javascript
原生node.js案例--前后台交互
2017/02/20 Javascript
Bootstrap禁用响应式布局的实现方法
2017/03/09 Javascript
使用AngularJS编写多选按钮选中时触发指定方法的指令代码详解
2017/07/24 Javascript
jQuery实现的自定义轮播图功能详解
2018/12/28 jQuery
JavaScript设计模式之观察者模式实例详解
2019/01/16 Javascript
微信小程序实现列表的横向滑动方式
2020/07/15 Javascript
js实现tab栏切换效果
2020/08/02 Javascript
[59:32]Liquid vs Fnatic 2019国际邀请赛淘汰赛败者组BO1 8.20.mp4
2020/07/19 DOTA
利用Anaconda完美解决Python 2与python 3的共存问题
2017/05/25 Python
python实现指定字符串补全空格、前面填充0的方法
2018/11/16 Python
python3+opencv3识别图片中的物体并截取的方法
2018/12/05 Python
linux环境中没有网络怎么下载python
2019/07/07 Python
pyinstaller打包opencv和numpy程序运行错误解决
2019/08/16 Python
python shapely.geometry.polygon任意两个四边形的IOU计算实例
2020/04/12 Python
python安装第三方库如xlrd的方法
2020/10/31 Python
网购亚洲时装、美容产品和生活百货:YesStyle
2016/09/15 全球购物
优秀英语专业毕业生求职信
2013/11/23 职场文书
工业学校毕业生自荐书
2014/01/03 职场文书
新年联欢会主持词
2014/03/27 职场文书
支行行长竞聘演讲稿
2014/05/15 职场文书
医院节能减排方案
2014/06/13 职场文书
小学国庆节活动方案策划书
2014/09/16 职场文书
违反工作规定检讨书范文
2014/12/14 职场文书
运动会新闻稿
2015/07/17 职场文书
升级 Win11 还是坚守 Win10?微软 Win11 新系统缺失功能大盘点
2022/04/05 数码科技