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 多维切片之冒号和三个点的用法介绍
Apr 19 Python
对python:print打印时加u的含义详解
Dec 15 Python
python中import与from方法总结(推荐)
Mar 21 Python
使用python实现离散时间傅里叶变换的方法
Sep 02 Python
手动安装python3.6的操作过程详解
Jan 13 Python
Tensorflow 卷积的梯度反向传播过程
Feb 10 Python
Python操作Jira库常用方法解析
Apr 10 Python
解决jupyter notebook import error但是命令提示符import正常的问题
Apr 15 Python
Windows下Anaconda安装、换源与更新的方法
Apr 17 Python
Pycharm调试程序技巧小结
Aug 08 Python
Python如何爬取b站热门视频并导入Excel
Aug 10 Python
Python安装并操作redis实现流程详解
Oct 13 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在字符串中查找另一个字符串
2008/11/19 PHP
基于php伪静态的实现详细介绍
2013/04/28 PHP
带密匙的php加密解密示例分享
2014/01/29 PHP
php实现的用户查询类实例
2015/06/18 PHP
PHP中substr_count()函数获取子字符串出现次数的方法
2016/01/07 PHP
非常有用的9个PHP代码片段
2016/04/06 PHP
微信接口生成带参数的二维码
2017/07/31 PHP
jquery上传插件fineuploader上传文件使用方法(jquery图片上传插件)
2013/12/05 Javascript
介绍JavaScript中Math.abs()方法的使用
2015/06/14 Javascript
用JavaScript判断CSS浏览器类型前缀的两种方法
2015/10/08 Javascript
JSON 的正确用法探讨:Pyhong、MongoDB、JavaScript与Ajax
2016/05/15 Javascript
使用JQuery中的trim()方法去掉前后空格
2016/09/16 Javascript
完全深入学习Bootstrap表单
2016/11/28 Javascript
JS实现的二叉树算法完整实例
2017/04/06 Javascript
微信小程序五星评分效果实现代码
2017/04/06 Javascript
extjs简介_动力节点Java学院整理
2017/07/17 Javascript
Angular弹出模态框的两种方式
2017/10/19 Javascript
layer.alert回调函数执行关闭弹窗的实例
2019/09/11 Javascript
JavaScript运行机制实例分析
2020/04/11 Javascript
原生JavaScript写出Tabs标签页的实例代码
2020/07/20 Javascript
[01:08:00]Fnatic vs Winstrike 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
[05:24]TI9采访——教练
2019/08/24 DOTA
python实现获取序列中最小的几个元素
2014/09/25 Python
Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】
2018/12/05 Python
使用tqdm显示Python代码执行进度功能
2019/12/08 Python
python 读写文件包含多种编码格式的解决方式
2019/12/20 Python
python实现处理mysql结果输出方式
2020/04/09 Python
python线程池如何使用
2020/05/28 Python
哥伦比亚最大的网上商店:Linio哥伦比亚
2016/09/25 全球购物
巴塞罗那观光通票:Barcelona Pass
2019/10/30 全球购物
实习教师自我鉴定
2013/09/27 职场文书
党校学习心得体会范文
2014/09/09 职场文书
我的职业生涯规划:打造自己的运动帝国
2014/09/18 职场文书
舞出我人生观后感
2015/06/16 职场文书
团拜会主持词
2015/07/04 职场文书
MySQL多表查询机制
2022/03/17 MySQL