测试图片

一、相对路径(报错)

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

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)

到此这篇关于python xlwings插入excel图片的实现方法的文章就介绍到这了,更多相关python xlwings插入图片内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!