python:xlwings 操作 Excel 加入图片

pip install xlwings ;

xlwings-0.28.5-cp37-cp37m-win_amd64.whl (1.6 MB)

摘要:Make Excel fly: Interact with Excel from Python and vice versa.

Requires: pywin32

编写 xlwings_test.py 如下

python 复制代码
# -*- coding: utf-8 -*-
""" xlwings 结合 Matplotlib 运用,能将图片加入 Excel文件中"""
import matplotlib.pyplot as plt
import xlwings as xw

fig = plt.figure()  # 指定画布
# plt.plot([1, 2, 3, 4, 5])
plt.plot([36,5,3,25,78])
plt.plot([9,10,31,45])
plt.plot([6,14,45,31])
plt.savefig(r'd:\python\test.png')

book = xw.Book(r'D:/python/test.xlsx')
sheet = book.sheets[0]
#help(sheet.pictures)
#add(self, image, link_to_file=False, save_with_document=True,
#    left=None, top=None, width=None, height=None, name=None, update=False,
#    scale=None, format=None, anchor=None, export_options=None)
sheet.pictures.add(fig, left=100, top=100, name='mypic', update=True)
book.save(r'd:\python\test.xlsx')
book.close()

运行 python xlwings_test.py


pip install openpyxl ;

openpyxl-3.1.2-py2.py3-none-any.whl (249 kB)

et_xmlfile-1.1.0-py3-none-any.whl (4.7 kB)

摘要:A Python library to read/write Excel 2010 xlsx/xlsm files

编写 openpyxl_test1.py 如下

python 复制代码
# -- coding: utf-8 --
""" 插入一个图片,需要先安装 Pillow (PIL)"""
from openpyxl import load_workbook
from openpyxl.drawing.image import Image

book = load_workbook("d:/python/test1.xlsx")
sheet = book.active
img = Image(r'd:\python\test.png')
nrows = sheet.max_row    # 取最大行数
#help(sheet.add_image)
# sheet.add_image(img, anchor=None)
sheet.add_image(img, "B%d" %(nrows+2))
#print("B%d" %(nrows+2))
book.save("d:/python/test1.xlsx")

运行 python openpyxl_test1.py

注意: anchor='A1' # cell 表格中位置,我选取了'B6'

相关推荐
TTGGGFF1 天前
Supertonic 部署与使用全流程保姆级指南(附已部署镜像)
开发语言·python
love530love1 天前
升级到 ComfyUI Desktop v0.7.0 版本后启动日志报 KeyError: ‘tensorrt‘ 错误解决方案
开发语言·windows·python·pycharm·virtualenv·comfyui·comfyui desktop
落羽凉笙1 天前
Python学习笔记(3)|数据类型、变量与运算符:夯实基础,从入门到避坑(附图解+代码)
笔记·python·学习
Quintus五等升1 天前
深度学习①|线性回归的实现
人工智能·python·深度学习·学习·机器学习·回归·线性回归
天远Date Lab1 天前
Python实战:对接天远数据手机号码归属地API,实现精准用户分群与本地化运营
大数据·开发语言·python
哈里谢顿1 天前
Python异常链:谁才是罪魁祸首?一探"The above exception"的时间顺序
python
哈里谢顿1 天前
验证 list() 会调用 `__len__` 方法的深度解析
python·django
vibag1 天前
构建智能体与工具调用
python·语言模型·大模型·langgraph
小途软件1 天前
高校宿舍访客预约管理平台开发
java·人工智能·pytorch·python·深度学习·语言模型
-dcr1 天前
49.python自动化
运维·python·自动化