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'

相关推荐
diediedei11 小时前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
m0_5613596711 小时前
使用Python自动收发邮件
jvm·数据库·python
naruto_lnq11 小时前
用Python批量处理Excel和CSV文件
jvm·数据库·python
b20772112 小时前
Flutter for OpenHarmony 身体健康状况记录App实战 - 提醒设置实现
python·flutter·macos·cocoa·harmonyos
2301_8223650312 小时前
数据分析与科学计算
jvm·数据库·python
河北小博博12 小时前
分布式系统稳定性基石:熔断与限流的深度解析(附Python实战)
java·开发语言·python
黄连升12 小时前
Python学习第二天,系统学习基础
python·学习
西红市杰出青年12 小时前
CSS 选择器详细教程:原理、语法、方向/“轴”与实战
css·python
tudficdew12 小时前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
爱学习的阿磊12 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python