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'

相关推荐
pingzhuyan24 分钟前
python入门篇12-虚拟环境conda的安装与使用
python·ai·llm·ocr·conda
香蕉可乐荷包蛋26 分钟前
排序算法 (Sorting Algorithms)-Python示例
python·算法·排序算法
菜鸟学Python2 小时前
Python web框架王者 Django 5.0发布:20周年了!
前端·数据库·python·django·sqlite
旧时光巷4 小时前
【机器学习-4】 | 集成学习 / 随机森林篇
python·随机森林·机器学习·集成学习·sklearn·boosting·bagging
Ice__Cai4 小时前
Django + Celery 详细解析:构建高效的异步任务队列
分布式·后端·python·django
MediaTea4 小时前
Python 库手册:doctest 文档测试模块
开发语言·python·log4j
2025年一定要上岸4 小时前
【pytest高阶】源码的走读方法及插件hook
运维·前端·python·pytest
angushine4 小时前
Python将Word转换为Excel
python·word·excel
抠头专注python环境配置5 小时前
Anaconda创建环境报错:CondaHTTPEFTOT: HTTP 403 FORBIDDEN for url
python·conda
王者鳜錸5 小时前
PYTHON从入门到实践-15数据可视化
开发语言·python·信息可视化