百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

使用 Python 在 Excel 中插入、压缩、替换、提取和删除图像

off999 2025-04-30 18:49 18 浏览 0 评论

Excel 不仅仅是一个数字和公式的工具;它还提供了用于处理图像的强大功能。无论您是创建报告、演示文稿还是数据可视化,合并图像都可以大大提高 Excel 项目的整体影响力和专业性。

在 Excel 中处理图像的 Python 库

要在 Excel 中插入、压缩、替换、提取和删除图像,我们将使用 Spire.XLS for Python 库。

可以通过在终端中运行以下命令从 PyPI 安装 Spire.XLS for Python:

pip install Spire.Xls

有关安装的更多详细信息,可以查看以下官方文档:

  • 如何在 Windows 上安装 Spire.XLS for Python
  • 如何在 Mac 上安装 Spire.XLS for Python

使用 Python 在 Excel 单元格中插入图像

将图像集成到电子表格中可以通过提供视觉上下文和支持信息来增强数据的整体呈现和交流。

Spire.XLS for Python 中的 Worksheet.Pictures.Add() 函数用于将图像插入 Excel 单元格。这是一个简单的示例,展示了我们如何使用此功能将本地文件中的图像插入 Excel 单元格:

from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Specify the cell to add the image
range = sheet.Range["C2"]

# Specify the path to the image you want to insert
image_path = "Medium.png"

# Insert the image into the worksheet
image = sheet.Pictures.Add(range.Row, range.Column, image_path)

# Set the properties of the image  
image.ResizeBehave = ResizeBehaveType.MoveNotResize # move but don't size with cells
# Set the left column and top row offsets for the image
image.LeftColumnOffset = 25
image.TopRowOffset = 25

# Set the height of the row where the cell is located
sheet.SetRowHeight(range.Row, 35)
# Set the width of the column where the cell is located
sheet.SetColumnWidth(range.Column, 17)

# Save the resulting file
workbook.SaveToFile("InsertLocalImage.xlsx", FileFormat.Version2013)
workbook.Dispose()

使用 Python 在 Excel 单元格中插入在线图像

除了将本地文件中的图像插入 Excel 之外,您还可以从外部 Web 链接插入在线图像。使用 Spire.XLS for Python 有两种方法可以实现此目的:

1. 链接到外部 Web 资源:

  • 使用 Spire.XLS 提供的 Worksheet.Pictures.AddLinkPic() 函数。
  • 使用此方法时,图像不会嵌入到 Excel 文件中。相反,它指向外部 Web 资源。
  • 在 Microsoft Excel 中打开电子表格时,应用程序将自动从指定的 URL 下载图像并将其显示在工作表中。

此方法的优点:

  • 较小的文件大小:Excel 文件大小保持较小,因为图像数据未存储在文件中。
  • 动态更新:如果外部 URL 中的图像已更新,则更改将在打开 Excel 电子表格时反映在 Excel 电子表格中。
  • 降低存储要求:Excel 文件不需要存储图像数据,这对于大型或高分辨率图像非常有用。

可能的缺点:

  • 对外部资源的依赖:仅当外部 URL 可访问时,才会显示图像。如果图像被移动或 URL 发生更改,图像可能无法在电子表格中正确显示。
  • 性能:根据 Internet 连接速度,每次打开电子表格时频繁地从外部 URL 下载图像可能会影响电子表格的性能和加载时间。

以下示例显示了如何通过链接到外部 Web 资源将在线图像插入 Excel:

from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Specify the cell to add the image
range = sheet.Range["C2"]

# Specify the URL of the image you want to insert
image_url = "https://i.ibb.co/dJ8h49F/Medium.png"
# Specify image width and height
image_width = 35
image_height = 116

# Link to the external image resource
image = sheet.Pictures.AddLinkPic(range.Row, range.Column, image_width, image_height, image_url)
# Set the properties of the image to “move but don't size with cells”
image.ResizeBehave = ResizeBehaveType.MoveNotResize
# Set the left column and top row offsets for the image
image.LeftColumnOffset = 25
image.TopRowOffset = 25

# Set the height of the row where the cell is located
sheet.SetRowHeight(range.Row, 35)
# Set the width of the column where the cell is located
sheet.SetColumnWidth(range.Column, 17)

# Save the resulting file
workbook.SaveToFile("InsertOnlineImage.xlsx", FileFormat.Version2013)
workbook.Dispose()

2. 嵌入图像:

  • 使用 Python 的内置模块 urllib 从图像链接中读取图像数据。
  • 使用 Spire.XLS 提供的 Worksheet.Pictures.AddPicture() 函数将图像数据添加到 Excel。
  • 此方法将图像数据直接嵌入到 Excel 文件中。
  • 由于数据存储在 Excel 文件中,因此无需任何外部下载即可显示图像。

下面的示例显示了如何通过嵌入图像将在线图像插入 Excel 中:

from spire.xls import *
from spire.xls.common import *
import urllib.request

# Create a Workbook object
workbook = Workbook()

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Specify the cell to add the image
range = sheet.Range["C2"]

# Specify the URL of the image you want to insert
image_url = "https://i.ibb.co/dJ8h49F/Medium.png"

# Use urllib to read the image data from the URL
with urllib.request.urlopen(image_url) as response:
    image_data = response.read()

# Add the image to the worksheet
stream = Stream(image_data)
image = sheet.Pictures.Add(range.Row, range.Column, stream)

# Set the properties of the image to “move but don't size with cells”
image.ResizeBehave = ResizeBehaveType.MoveNotResize
# Set the left column and top row offsets for the image
image.LeftColumnOffset = 25
image.TopRowOffset = 25

# Set the height of the row where the cell is located
sheet.SetRowHeight(range.Row, 35)
# Set the width of the column where the cell is located
sheet.SetColumnWidth(range.Column, 17)

# Save the resulting file
workbook.SaveToFile("InsertOnlineImage.xlsx", FileFormat.Version2013)
workbook.Dispose()

使用 Python 在 Excel 中压缩图像

当您需要减小包含大图像或高分辨率图像的 Excel 文件的大小时,在 Excel 中压缩图像非常有用。

要压缩 Excel 文件中的图像,您需要遍历每个 Excel 工作表中的图像,然后调用 ExcelPicture.Compress() 函数来压缩每个图像的质量。下面是代码示例:

from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Images.xlsx")

# Iterate through the worksheets in the file
for sheet in workbook.Worksheets:
    # Iterate through the images in the worksheet
    for image in sheet.Pictures:
        # Compress the image quality
        image.Compress(50)

# Save the resulting file
workbook.SaveToFile("CompressImages.xlsx", FileFormat.Version2013)
workbook.Dispose()

用 Python 替换 Excel 中的图像

有时您可能需要将 Excel 工作表中的旧图像更改为新图像。为此,您可以使用 ExcelPicture.Picture 属性。

下面的示例显示了如何将 Excel 工作表中的图像替换为另一个图像:

from spire.xls import *
from spire.xls.common import *

# Create a Workbook instance 
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile ("Images.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Get the first image from the worksheet
excelPicture = sheet.Pictures[0]
            
# Specify the path to the new image
image_path = "logo.png"
# Replace the first image with the new image
stream = Stream(image_path)
excelPicture.Picture = stream

# Save the resulting file
workbook.SaveToFile("ReplaceImage.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

使用 Python 从 Excel 中提取图像

如果您需要将嵌入在 Excel 工作簿中的图像用于其他目的,例如在演示文稿或网站上,则提取过程是必不可少的。

要从 Excel 文件中提取图像,您可以使用 ExcelPicture.Picture.Save() 函数。下面是代码示例:

from spire.xls import *
from spire.xls.common import *

# Create a new Workbook instance
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Images.xlsx")

# Iterate through the worksheets in the workbook
for worksheet_index, worksheet in enumerate(workbook.Worksheets):
    # Iterate through the images in the worksheet
    for image_index, image in enumerate(worksheet.Pictures):
        # Save each image as a PNG file
        image_path = f"Images/Worksheet_{worksheet_index+1}_Image_{image_index+1}.png"
        image.Picture.Save(image_path)

workbook.Dispose()

使用 Python 从 Excel 中删除图像

当您想整理电子表格或删除不再需要的图像时,从 Excel 中删除图像非常有用。

您可以使用 Worksheet.Pictures[index] 从 Excel 工作表中删除一个或多个图像。Remove() 函数。下面是代码示例:

from spire.xls import *
from spire.xls.common import *

# Create a new Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Images.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Remove all images from the worksheet
for i in range(sheet.Pictures.Count - 1, -1, -1):
    sheet.Pictures[i].Remove()

# Or remove a specific image by its index (0-based)
# sheet.Pictures[0].Remove()

# Save the resulting file
workbook.SaveToFile("RemoveImages.xlsx", FileFormat.Version2013)
workbook.Dispose()


相关推荐

推荐一款Python的GUI可视化工具(python 可视化工具)

在Python基础语法学习完成后,进一步开发应用界面时,就需要涉及到GUI了,GUI全称是图形用户界面(GraphicalUserInterface,又称图形用户接口),采用图形方式显示的计算机操...

教你用Python绘制谷歌浏览器的3种图标

前两天在浏览matplotlib官方网站时,笔者无意中看到一个挺有意思的图片,就是用matplotlib制作的火狐浏览器的logo,也就是下面这个东东(网页地址是https://matplotlib....

小白学Python笔记:第二章 Python安装

Windows操作系统的python安装:Python提供Windows、Linux/UNIX、macOS及其他操作系统的安装包版本,结合自己的使用情况,此处仅记录windows操作系统的python...

Python程序开发之简单小程序实例(9)利用Canvas绘制图形和文字

Python程序开发之简单小程序实例(9)利用Canvas绘制图形和文字一、项目功能利用Tkinter组件中的Canvas绘制图形和文字。二、项目分析要在窗体中绘制图形和文字,需先导入Tkinter组...

一文吃透Python虚拟环境(python虚拟环境安装和配置)

摘要在Python开发中,虚拟环境是一种重要的工具,用于隔离不同项目的依赖关系和环境配置。本文将基于windows平台介绍四种常用的Python虚拟环境创建工具:venv、virtualenv、pip...

小白也可以玩的Python爬虫库,收藏一下

最近,微软开源了一个项目叫「playwright-python」,作为一个兴起项目,出现后受到了大家热烈的欢迎,那它到底是什么样的存在呢?今天为你介绍一下这个传说中的小白神器。Playwright是...

python环境安装+配置教程(python安装后怎么配置环境变量)

安装python双击以下软件:弹出一下窗口需选择一些特定的选项默认选项不需要更改,点击next勾选以上选项,点击install进度条安装完毕即可。到以下界面,证明安装成功。接下来安装库文件返回电脑桌面...

colorama,一个超好用的 Python 库!

大家好,今天为大家分享一个超好用的Python库-colorama。Github地址:https://github.com/tartley/coloramaPythoncolorama库是一...

python制作仪表盘图(python绘制仪表盘)

今天教大家用pyecharts画仪表盘仪表盘(Gauge)是一种拟物化的图表,刻度表示度量,指针表示维度,指针角度表示数值。仪表盘图表就像汽车的速度表一样,有一个圆形的表盘及相应的刻度,有一个指针...

总结90条写Python程序的建议(python写作)

  1.首先  建议1、理解Pythonic概念—-详见Python中的《Python之禅》  建议2、编写Pythonic代码  (1)避免不规范代码,比如只用大小写区分变量、使用容易...

[oeasy]python0137_相加运算_python之禅_import_this_显式转化

变量类型相加运算回忆上次内容上次讲了是从键盘输入变量input函数可以有提示字符串需要有具体的变量接收输入的字符串输入单个变量没有问题但是输入两个变量之后一相加就非常离谱添加图片注释,不超过1...

Python入门学习记录之一:变量(python中变量的规则)

写这个,主要是对自己学习python知识的一个总结,也是加深自己的印象。变量(英文:variable),也叫标识符。在python中,变量的命名规则有以下三点:>变量名只能包含字母、数字和下划线...

掌握Python的"魔法":特殊方法与属性完全指南

在Python的世界里,以双下划线开头和结尾的"魔法成员"(如__init__、__str__)是面向对象编程的核心。它们赋予开发者定制类行为的超能力,让自定义对象像内置类型一样优雅工...

11个Python技巧 不Pythonic 实用大于纯粹

虽然Python有一套强大的设计哲学(体现在“Python之禅”中),但总有一些情况需要我们“打破规则”来解决特定问题。这触及了Python哲学中一个非常核心的理念:“实用主义胜于纯粹主义”...

Python 从入门到精通 第三课 诗意的Python之禅

导言:Python之禅,英文名是TheZenOfPython。最早由TimPeters在Python邮件列表中发表,它包含了影响Python编程语言设计的20条软件编写原则。它作为复活节彩蛋...

取消回复欢迎 发表评论: