實際上ofd、docx、xlsx等文件就是一個壓縮文件,是可以被解壓處理的。所以我們把一個ofd格式的發票文件解壓后就可以看到它的目錄,如下:

再用谷歌或者IE打開里面的xml屬性的文件,就可以看到發票相關信息,如下:

所以獲取發票信息的實現方法大致就是:先解壓ofd格式文件,得到里面的OFD.xml文件,在通過解析xml文件獲取到發票相關信息
解析xml文件
from xml.dom.minidom import parse
def get_info(dir_path, unzip_file_path=None, removed=True):
"""
:param dir_path: 壓縮文件路徑
:param unzip_file_path: 解壓后的文件路徑
:param removed: 是否刪除解壓后的目錄
:return: ofd_info,字典形式的發票信息
"""
file_path = unzip_file(dir_path, unzip_file_path)
io = f"{file_path}/OFD.xml"
element = parse(io).documentElement
nodes = element.getElementsByTagName('ofd:CustomDatas')
ofd_info = {}
for i in range(len(nodes)):
sun_node = nodes[i].childNodes
for j in range(len(sun_node)):
name = sun_node[j].getAttribute('Name')
value = sun_node[j].firstChild.data
ofd_info[name] =value
if removed:
shutil.rmtree(unzip_path)
return ofd_info
解壓ofd文件
import shutil
import zipfile
def unzip_file(zip_path, unzip_path=None):
"""
:param zip_path: ofd格式文件路徑
:param unzip_path: 解壓后的文件存放目錄
:return: unzip_path
"""
if not unzip_path:
unzip_path = zip_path.split('.')[0]
with zipfile.ZipFile(zip_path, 'r') as f:
for file in f.namelist():
f.extract(file, path=unzip_path)
return unzip_path
結果顯示

