Python读取wps中的DISPIMG图片格式

2024-06-16 06:28

本文主要是介绍Python读取wps中的DISPIMG图片格式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

需求:
读出excel的图片内容,这放在微软三件套是很容易的,但是由于wps的固有格式,会出现奇怪的问题,只能读出:类似于 =DISPIMG(“ID_2B83F9717AE1XXXX920xxxx644C80DB1”,1) 【该DISPIMG函数只有wps才拥有】

本文参考该多个作者的思路:
https://blog.csdn.net/maudboy/article/details/133145278 java读取Excel,(支持WPS嵌入式图片)
以及该github issus:
https://github.com/qax-os/excelize/issues/664 How to read pictures embedded in cells
当然该项目两个个月前用go 来读取wps中的图片格式:https://github.com/qax-os/excelize excelize

希望大家多多关注

github前几名的excel读取,python在后几名【这让我挺吃惊的,作为第一语言,支持库这么多,竟然没有对wps图片解析的python代码】,第一是Go写的。
在这里插入图片描述

首先明确,xlsx就是一个zip包,否则里面的图片根本没法读取。
下面是该代码的思路:

# xlsx本质就是zip,其解压文件夹为_rels xl docProps
# 代码思路:首先读取excel表,并提取DISPIMG_id列,保存在image_list中
# 根据xl/cellimages.xml 提取出rId与DISPIMG_id的关系,组成一个map1,{"DISPIMG_id":"rId"}
# 再根据xl/_rels/cellimages.xml.rels,根据rId 与 imgae_path的关系,组成一个map2 {"rId":"image_path"}
# 根据map1与map2对应的关系,组成一个新map3 : {"DISPIMG_id": "image_path"} 得出对应的关系
# 输出图片,根据xl/{image_path} 输出图片并把图片重命名为DISPIMG_id.png

代码思路,该代码可以优化,主要多次读取文件并且多次调用map了,不过处理几百条数据还是绰绰有余的。

import zipfile
import os
import xml.etree.ElementTree as ET
import openpyxlimage_list = []  # 存放从excel读出的DISPIMG_iddef read_excel_data(filename_path):# 加载 Excel 文件workbook = openpyxl.load_workbook(filename_path, data_only=False)sheet = workbook.active# 遍历数据和公式data = [] # data就是文本信息for row in sheet.iter_rows(min_row=1, values_only=False):row_data = []for cell in row:if cell.value and isinstance(cell.value, str) and '=_xlfn.DISPIMG(' in cell.value:# 提取嵌入的图片 IDformula = cell.valuestart = formula.find('"') + 1end = formula.find('"', start)image_id = formula[start:end]row_data.append(f"{image_id}")image_list.append(image_id)# print(image_id)else:# 其他数据直接添加row_data.append(cell.value)data.append(row_data)return datadef get_xml_id_image_map(xlsx_file_path):# 打开 XLSX 文件with zipfile.ZipFile(xlsx_file_path, 'r') as zfile:# 直接读取 XML 文件内容with zfile.open('xl/cellimages.xml') as file:xml_content = file.read()with zfile.open('xl/_rels/cellimages.xml.rels') as file:relxml_content = file.read()# 将读取的内容转换为 XML 树root = ET.fromstring(xml_content)# 初始化映射字典name_to_embed_map = {}# 命名空间namespaces = {'xdr': 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing','a': 'http://schemas.openxmlformats.org/drawingml/2006/main'}# 遍历所有 pic 元素for pic in root.findall('.//xdr:pic', namespaces=namespaces):name = pic.find('.//xdr:cNvPr', namespaces=namespaces).attrib['name']embed = pic.find('.//a:blip', namespaces=namespaces).attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed']name_to_embed_map[name] = embed# 打印结果# print(name_to_embed_map)root1 = ET.fromstring(relxml_content)# 命名空间字典,根据 XML 中定义的命名空间进行设置namespaces = {'r': 'http://schemas.openxmlformats.org/package/2006/relationships'}# 创建 ID 和 Target 的映射id_target_map = {child.attrib['Id']: child.attrib.get('Target', 'No Target Found') for child inroot1.findall('.//r:Relationship', namespaces=namespaces)}# print(id_target_map)# 使用字典推导构建新的映射表name_to_target_map = {name: id_target_map[embed] for name, embed in name_to_embed_map.items() ifembed in id_target_map}return name_to_target_mapdef output_id_image(xlsx_file_path):read_excel_data(xlsx_file_path)name_to_target_map = get_xml_id_image_map(xlsx_file_path)# 构建id_image_对new_map = {key: name_to_target_map.get(key) for key in image_list if key in name_to_target_map}print(new_map)output_directory = './images' #保存的图片目录# 打开xlsx文件(即Zip文件)with zipfile.ZipFile(xlsx_file_path, 'r') as zfile:for key, image_path in new_map.items():# 构建实际的图片路径actual_image_path = f'xl/{image_path}'  # 假设图片在'xl/media/'目录下if actual_image_path in zfile.namelist():# 读取图片内容with zfile.open(actual_image_path) as image_file:image_content = image_file.read()# 保存图片到新的文件,使用key作为文件名new_file_path = os.path.join(output_directory, f"{key}.png")with open(new_file_path, 'wb') as new_file:new_file.write(image_content)else:print(f"File {actual_image_path} not found in the archive.")if __name__ == '__main__':output_id_image('/home/jacin/Downloads/英式货表.xlsx')# 输出的图片名字就是 xlsx表中的列的DISPIMG_id,保存在images文件夹下# 并会在控制台输出一个字典,key是DISPIMG_id,value是图片的路径,例如:{'ID_BE7EFF591B6C4978XXXXXX5266': 'media/image118.png'}

这篇关于Python读取wps中的DISPIMG图片格式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1065696

相关文章

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

Python运行中频繁出现Restart提示的解决办法

《Python运行中频繁出现Restart提示的解决办法》在编程的世界里,遇到各种奇怪的问题是家常便饭,但是,当你的Python程序在运行过程中频繁出现“Restart”提示时,这可能不仅仅是令人头疼... 目录问题描述代码示例无限循环递归调用内存泄漏解决方案1. 检查代码逻辑无限循环递归调用内存泄漏2.

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

Python如何自动生成环境依赖包requirements

《Python如何自动生成环境依赖包requirements》:本文主要介绍Python如何自动生成环境依赖包requirements问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录生成当前 python 环境 安装的所有依赖包1、命令2、常见问题只生成当前 项目 的所有依赖包1、

如何将Python彻底卸载的三种方法

《如何将Python彻底卸载的三种方法》通常我们在一些软件的使用上有碰壁,第一反应就是卸载重装,所以有小伙伴就问我Python怎么卸载才能彻底卸载干净,今天这篇文章,小编就来教大家如何彻底卸载Pyth... 目录软件卸载①方法:②方法:③方法:清理相关文件夹软件卸载①方法:首先,在安装python时,下

python uv包管理小结

《pythonuv包管理小结》uv是一个高性能的Python包管理工具,它不仅能够高效地处理包管理和依赖解析,还提供了对Python版本管理的支持,本文主要介绍了pythonuv包管理小结,具有一... 目录安装 uv使用 uv 管理 python 版本安装指定版本的 Python查看已安装的 Python

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t