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制作在地图上模拟瘟疫扩散的Gif图
Mar 31 Python
python下MySQLdb用法实例分析
Jun 08 Python
深入理解Python变量与常量
Jun 02 Python
Python实现的科学计算器功能示例
Aug 04 Python
Python使用ConfigParser模块操作配置文件的方法
Jun 29 Python
浅谈利用numpy对矩阵进行归一化处理的方法
Jul 11 Python
python获取服务器响应cookie的实例
Dec 28 Python
python 根据时间来生成唯一的字符串方法
Jan 14 Python
Django uwsgi Nginx 的生产环境部署详解
Feb 02 Python
python中用logging实现日志滚动和过期日志删除功能
Aug 20 Python
python3检查字典传入函数键是否齐全的实例
Jun 05 Python
Python-typing: 类型标注与支持 Any类型详解
May 10 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
php实现12306余票查询、价格查询示例
2014/04/17 PHP
PHP简单字符串过滤方法示例
2016/09/04 PHP
thinkPHP和onethink微信支付插件分享
2019/08/11 PHP
javascript基于jQuery的表格悬停变色/恢复,表格点击变色/恢复,点击行选Checkbox
2008/08/05 Javascript
jQuery checkbox全选/取消全选实现代码
2009/11/14 Javascript
JavaScript 浏览器验证代码(来自discuz)
2010/07/17 Javascript
javascript 闭包
2011/09/15 Javascript
js实现拖拽 闭包函数详细介绍
2012/11/25 Javascript
Jquery chosen动态设置值实例介绍
2013/08/08 Javascript
Nodejs中自定义事件实例
2014/06/20 NodeJs
jquery通过load获取文件的内容并跳到锚点的方法
2015/01/29 Javascript
js实现点击图片改变页面背景图的方法
2015/02/28 Javascript
Javascript监视变量变化的方法
2015/06/09 Javascript
移除AngularJS下URL中的#字符的方法
2015/06/19 Javascript
javascript图片滑动效果实现
2021/01/28 Javascript
JS加载iFrame出现空白问题的解决办法
2016/05/13 Javascript
js设置文字颜色的方法示例
2016/12/30 Javascript
vue使用stompjs实现mqtt消息推送通知
2017/06/22 Javascript
vue-cli构建项目使用 less的方法
2017/10/04 Javascript
vue展示dicom文件医疗系统的实现代码
2018/08/27 Javascript
[02:51]DOTA2英雄基础教程 风暴之灵
2013/12/23 DOTA
python 文件和路径操作函数小结
2009/11/23 Python
python模拟登陆阿里妈妈生成商品推广链接
2014/04/03 Python
pandas带有重复索引操作方法
2018/06/08 Python
深入理解Python中的 __new__ 和 __init__及区别介绍
2018/09/17 Python
python3实现elasticsearch批量更新数据
2019/12/03 Python
python隐藏类中属性的3种实现方法
2019/12/19 Python
Django-rest-framework中过滤器的定制实例
2020/04/01 Python
keras处理欠拟合和过拟合的实例讲解
2020/05/25 Python
Myprotein亚太地区:欧洲第一在线运动营养品牌
2020/12/20 全球购物
文明寝室标语
2014/06/13 职场文书
公安民警正风肃纪剖析材料
2014/10/10 职场文书
2014年绩效考核工作总结
2014/12/11 职场文书
幼儿教师2014年度工作总结
2014/12/16 职场文书
2015年派出所民警工作总结
2015/04/24 职场文书
初二英语教学反思
2016/02/15 职场文书