Python如何读取Excel文件中形状内嵌文本框的内容?
通用Excel文本框/形状内嵌文本读取方案
要同时兼容.xls和.xlsx格式的内嵌文本读取,需要分别适配两种格式的底层结构,以下是可直接复用的实现思路和代码:
1. 格式适配逻辑
.xlsx格式:本质是ZIP压缩包,所有形状和文本框数据存放在xl/drawings/目录下的XML文件中,不需要依赖openpyxl的原生读取能力,直接解析XML即可拿到所有内嵌文本.xls格式:属于二进制OLE2格式,需要用xlrd结合olefile解析其中的Workbook流里的Office Drawing记录,提取文本框内容
2. 完整实现代码
首先安装依赖:
pip install openpyxl xlrd==1.2.0 olefile zipfile36
通用读取函数示例:
import zipfile import xml.etree.ElementTree as ET import xlrd def get_excel_shape_text(file_path: str) -> list: shape_texts = [] # 匹配xlsx/xlsm格式 if file_path.endswith(('.xlsx', '.xlsm')): with zipfile.ZipFile(file_path, 'r') as zf: # 遍历所有绘图文件 drawing_files = [f for f in zf.namelist() if f.startswith('xl/drawings/drawing') and f.endswith('.xml')] ns = {'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'} for df in drawing_files: xml_content = zf.read(df) root = ET.fromstring(xml_content) # 提取所有文本节点内容 text_nodes = root.findall('.//a:t', ns) for node in text_nodes: if node.text and node.text.strip(): shape_texts.append(node.text.strip()) # 匹配xls格式 elif file_path.endswith('.xls'): wb = xlrd.open_workbook(file_path, formatting_info=True) for sheet in wb.sheets(): if hasattr(sheet, 'shapes'): for shape in sheet.shapes: # 0x18为文本框的类型标识 if shape.type == 0x18 and hasattr(shape, 'text') and shape.text: shape_texts.append(shape.text.strip()) return shape_texts
3. 使用说明
- 提取到的文本可直接和原有单元格读取逻辑合并,共同写入数据库
- 如果需要关联文本框对应的单元格位置,可额外解析XML中的锚点属性、或xls格式中shape的位置字段进行匹配
- xls格式必须使用
xlrd==1.2.0版本,更高版本的xlrd已移除对xls格式二进制属性的读取支持
内容的提问来源于stack exchange,提问作者user2905416
相关产品推荐
相关产品推荐

