问题描述
我有一个the following pattern的Excel文件(data.xlsx),我需要从该Excel文件的文本框中读取值。
我当前正在使用Pandas库,我试图获取该值,但遗憾的是找不到任何用于该目标的API。
有人知道如何做到这一点吗?
更多信息:
我的问题与Java中的this姐妹问题重复。
编辑:
我为任何想知道如何手动(即不使用pip的外部模块)在Excel文件中搜索形状(可能还有所有其他项)的人提供了一个解决方案。实际上,这很简单。请参阅我的评论。
推荐答案
感谢所有的帮助,但这是我自己解决的。
我使用zipfile模块使其正常工作。显然,Excel is actually a suite that works on compressed XML files (changing the *.xlsx to *.zip reveals the contents of the file) when saving and reading from *.xlsx,所以我可以轻松地使用XML搜索所需的文本。
这是我制作的模块。通过调用Sheet('path/to/sheet.xlsx').shapes.text
,您现在可以轻松地找到文本框内的文本:
import zipfile as z
class Sheet(str):
@property
def shapes(this):
s = z.ZipFile(this)
p='xl/drawings/drawing1.xml' # shapes path, *.xlsx default
p='drs/shapexml.xml' # shapes path, *.xls default
return XML(s.read(p))
class XML(object):
def __init__(self, value):
self.value = str(value)
def __repr__(self):
return repr(self.value)
def __getitem__(self, i):
return self.value[i]
def tag_content(self, tag):
return [XML(i) for i in self.value.split(tag)[1::2]]
@property
def text(self):
t = self.tag_content('xdr:txBody') # list of XML codes, each containing a seperate textboxes, messy (with extra xml that is)
l = [i.tag_content('a:p>') for i in t] # split into sublists by line breaks (inside the textbox), messy
w = [[[h[1:-2] for h in i.tag_content('a:t')] if i else ['
'] for i in j] for j in l] # clean into sublists by cell-by-cell basis (and mind empty lines)
l = [[''.join(i) for i in j] for j in w] # join lines overlapping multiple cells into one sublist
return ['
'.join(j) for j in l] # join sublists of lines into strings seperated by newline char
所以现在我的问题中提供的模式将输出为['comments extra']
,而诸如:
将输出为['This isText in a textbox ona sheet','And this is another text box somewhere elseRegardless of the overlapped cells']
。
不客气。
这篇关于在Python中从Excel中获取文本框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!