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

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

off999 2025-04-30 18:49 24 浏览 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()


相关推荐

大文件传不动?WinRAR/7-Zip 入门到高手,这 5 个技巧让你效率翻倍

“这200张照片怎么传给女儿?微信发不了,邮箱附件又超限……”62岁的张阿姨对着电脑犯愁时,儿子只用了3分钟就把照片压缩成一个文件,还教她:“以后用压缩软件,比打包行李还方便!”职场人更懂这...

电脑解压缩软件推荐——7-Zip:免费、高效、简洁的文件管理神器

在日常工作中,我们经常需要处理压缩文件。无论是下载软件包、接收文件,还是存储大量数据,压缩和解压缩文件都成为了我们日常操作的一部分。而说到压缩解压软件,7-Zip绝对是一个不可忽视的名字。今天,我就来...

设置了加密密码zip文件要如何打开?这几个方法可以试试~

Zip是一种常见的压缩格式文件,文件还可以设置密码保护。那设置了密码的Zip文件要如何打开呢?不清楚的小伙伴一起来看看吧。当我们知道密码想要打开带密码的Zip文件,我们需要用到适用于Zip格式的解压缩...

大文件想要传输成功,怎么把ZIP文件分卷压缩

不知道各位小伙伴有没有这样的烦恼,发送很大很大的压缩包会受到限制,为此,想要在压缩过程中将文件拆分为几个压缩包并且同时为所有压缩包设置加密应该如何设置?方法一:使用7-Zip免费且强大的文件管理工具7...

高效处理 RAR 分卷压缩包:合并解压操作全攻略

在文件传输和存储过程中,当遇到大文件时,我们常常会使用分卷压缩的方式将其拆分成多个较小的压缩包,方便存储和传输。RAR作为一种常见的压缩格式,分卷压缩包的使用频率也很高。但很多人在拿到RAR分卷...

2个方法教你如何删除ZIP压缩包密码

zip压缩包设置了加密密码,每次解压文件都需要输入密码才能够顺利解压出文件,当压缩包文件不再需要加密的时候,大家肯定想删除压缩包密码,或是忘记了压缩包密码,想要通过删除操作将压缩包密码删除,就能够顺利...

速转!漏洞预警丨压缩软件Winrar目录穿越漏洞

WinRAR是一款功能强大的压缩包管理器,它是档案工具RAR在Windows环境下的图形界面。该软件可用于备份数据,缩减电子邮件附件的大小,解压缩从Internet上下载的RAR、ZIP及其它类...

文件解压方法和工具分享_文件解压工具下载

压缩文件减少文件大小,降低文件失效的概率,总得来说好处很多。所以很多文件我们下载下来都是压缩软件,很多小伙伴不知道怎么解压,或者不知道什么工具更好,所以今天做了文件解压方法和工具的分享给大家。一、解压...

[python]《Python编程快速上手:让繁琐工作自动化》学习笔记3

1.组织文件笔记(第9章)(代码下载)1.1文件与文件路径通过importshutil调用shutil模块操作目录,shutil模块能够在Python程序中实现文件复制、移动、改名和删除;同时...

Python内置tarfile模块:读写 tar 归档文件详解

一、学习目标1.1学习目标掌握Python内置模块tarfile的核心功能,包括:理解tar归档文件的原理与常见压缩格式(gzip/bz2/lzma)掌握tar文件的读写操作(创建、解压、查看、过滤...

使用python展开tar包_python拓展

类Unix的系统,打包文件经常使用的就是tar包,结合zip工具,可以方便的打包并解压。在python的标准库里面有tarfile库,可以方便实现生成了展开tar包。使用这个库最大的好处,可能就在于不...

银狐钓鱼再升级:白文件脚本化实现GO语言后门持久驻留

近期,火绒威胁情报中心监测到一批相对更为活跃的“银狐”系列变种木马。火绒安全工程师第一时间获取样本并进行分析。分析发现,该样本通过阿里云存储桶下发恶意文件,采用AppDomainManager进行白利...

ZIP文件怎么打开?2个简单方法教你轻松搞定!

在日常工作和生活中,我们经常会遇到各种压缩文件,其中最常见的格式之一就是ZIP。ZIP文件通过压缩数据来减少文件大小,方便我们进行存储和传输。然而,对于初学者来说,如何打开ZIP文件可能会成为一个小小...

Ubuntu—解压多个zip压缩文件.zip .z01 .z02

方法将所有zip文件放在同一目录中:zip_file.z01,zip_file.z02,zip_file.z03,...,zip_file.zip。在Zip3.0版本及以上,使用下列命令:将所有zi...

如何使用7-Zip对文件进行加密压缩

7-Zip是一款开源的文件归档工具,支持多种压缩格式,并提供了对压缩文件进行加密的功能。使用7-Zip可以轻松创建和解压.7z、.zip等格式的压缩文件,并且可以通过设置密码来保护压缩包中的...

取消回复欢迎 发表评论: