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

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

off999 2025-04-30 18:49 5 浏览 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 gui开发)

Python的GUI编程框架有很多,这里为您推荐几个常用且功能强大的框架:Tkinter:Tkinter是Python的标准GUI库,它是Python内置的模块,无需额外安装。它使用简单,功能较为基础...

python自动化框架学习-pyautogui(python接口自动化框架)

一、适用平台:PC(windows和mac均可用)二、下载安装:推荐使用命令行下载(因为会自动安装依赖库):pipinstallPyAutoGUI1该框架的依赖库还是蛮多的,第一次用的同学耐心等...

Python 失宠!Hugging Face 用 Rust 新写了一个 ML框架,现已低调开源

大数据文摘受权转载自AI前线整理|褚杏娟近期,HuggingFace低调开源了一个重磅ML框架:Candle。Candle一改机器学习惯用Python的做法,而是Rust编写,重...

Flask轻量级框架 web开发原来可以这么可爱呀~(建议收藏)

Flask轻量级框架web开发原来可以这么可爱呀大家好呀~今天让我们一起来学习一个超级可爱又实用的PythonWeb框架——Flask!作为一个轻量级的Web框架,Flask就像是一个小巧精致的工...

Python3使用diagrams生成架构图(python架构设计)

目录技术背景diagrams的安装基础逻辑关系图组件簇的定义总结概要参考链接技术背景对于一个架构师或者任何一个软件工程师而言,绘制架构图都是一个比较值得学习的技能。这就像我们学习的时候整理的一些Xmi...

几个高性能Python网络框架,高效实现网络应用

Python作为一种广泛使用的编程语言,其简洁易读的语法和强大的生态系统,使得它在Web开发领域占据重要位置。高性能的网络框架是构建高效网络应用的关键因素之一。本文将介绍几个高性能的Python网络框...

Web开发人员的十佳Python框架(python最好的web框架)

Python是一种面向对象、解释型计算机程序设计语言。除了语言本身的设计目的之外,Python的标准库也是值得大家称赞的,同时Python还自带服务器。其它方面,Python拥有足够多的免费数据函数库...

Diagram as Code:用python代码生成架构图

工作中常需要画系统架构图,通常的方法是通过visio、processon、draw.io之类的软件,但是今天介绍的这个软件Diagrams,可以通过写Python代码完成架构图绘制,确实很co...

分享一个2022年火遍全网的Python框架

作者:俊欣来源:关于数据分析与可视化最近Python圈子当中出来一个非常火爆的框架PyScript,该框架可以在浏览器中运行Python程序,只需要在HTML程序中添加一些Python代码即可实现。该...

10个用于Web开发的最好 Python 框架

Python是一门动态、面向对象语言。其最初就是作为一门面向对象语言设计的,并且在后期又加入了一些更高级的特性。除了语言本身的设计目的之外,Python标准库也是值得大家称赞的,Python甚至还...

使用 Python 将 Google 表格变成您自己的数据库

图片来自Shutterstock,获得FrankAndrade的许可您知道Google表格可以用作轻量级数据库吗?GoogleSheets是一个基于云的电子表格应用程序,可以像大多数数据库管...

牛掰!用Python处理Excel的14个常用操作总结!

自从学了Python后就逼迫用Python来处理Excel,所有操作用Python实现。目的是巩固Python,与增强数据处理能力。这也是我写这篇文章的初衷。废话不说了,直接进入正题。数据是网上找到的...

将python打包成exe的方式(将python文件打包成exe可运行文件)

客户端应用程序往往需要运行Python脚本,这对于那些不熟悉Python语言的用户来说可能会带来一定的困扰。幸运的是,Python拥有一些第三方模块,可以将这些脚本转换成可执行的.exe...

对比Excel学Python第1练:既有Excel,何用Python?

背景之前发的文章开头都是“Python数据分析……”,使得很多伙伴以为我是专门分享Python的,但我的本意并非如此,我的重点还是会放到“数据分析”上,毕竟,Python只是一种工具而已。现在网上可以...

高效办公:Python处理excel文件,摆脱无效办公

一、Python处理excel文件1.两个头文件importxlrdimportxlwt其中xlrd模块实现对excel文件内容读取,xlwt模块实现对excel文件的写入。2.读取exce...

取消回复欢迎 发表评论: