我有数千个 Excel 工作簿,需要创建一个列表,其中包含可能包含文本的形状(即文本框)。我将如何使用 openpyxl 或底层 XML 生成所有带有文本的形状的列表?我尝试使用 xlwings 和 pywin32,但是这些库解析形状的速度太慢而没有用处。
当前慢速代码:
for shape in ws_xlwings.shapes:
if shape.type == "text_box" or shape.type == "auto_shape":
try:
str_cell_value = shape.text.lower()
str_cell_value_upper = shape.text
except: #shape might not have text
continue
这里有一个关于如何将 Excel 作为 zip 文件处理、提取绘图 xml 和检测文本框的 POC。它可能比解析整个电子表格更快。
'''Based on https://rsmith.home.xs4all.nl/howto/reading-xlsx-files-with-python.html'''
from zipfile import ZipFile
from lxml import etree
def main():
z = ZipFile('/home/lmc/tmp/shapes.xlsx')
with z.open('xl/drawings/drawing1.xml') as sstr:
ssdata = sstr.read()
tree = etree.fromstring(ssdata)
ns = {"xdr": "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",
"a": "http://schemas.openxmlformats.org/drawingml/2006/main",
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
}
shapes = tree.xpath('//xdr:txBody[preceding-sibling::xdr:spPr]/a:p/a:r/a:t/text()', namespaces = ns)
print(shapes)
if __name__ == '__main__':
main()
带有 1 个方框的简单表格的结果
['Square box text']