Skip to main content
 首页 » 编程设计

python之从python中的.eml文件解析excel附件

2024年12月31日8linjiqin

我正在尝试解析 .eml 文件。 .eml 有一个 excel 附件,目前是 base 64 编码的。我正在尝试弄清楚如何将其解码为 XML,以便稍后可以将其转换为我可以使用的 CSV。

这是我现在的代码:

import email 
 
data = file('Openworkorders.eml').read() 
msg = email.message_from_string(data) 
 
for part in msg.walk(): 
    c_type = part.get_content_type() 
    c_disp = part.get('Content Disposition') 
 
 
    if part.get_content_type() == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 
        excelContents = part.get_payload(decode = True) 
 
        print excelContents 

问题是

当我尝试对其进行解码时,它会吐出类似这样的内容。

我用这篇文章来帮助我编写上面的代码。

How can I get an email message's text content using Python?

更新:

这与我的文件的帖子解决方案完全相同,但是 part.get_payload() 返回所有仍然编码的内容。我还没有弄清楚如何以这种方式访问​​解码后的内容。

import email 
 
 
data = file('Openworkorders.eml').read() 
msg = email.message_from_string(data) 
for part in msg.walk(): 
    if part.get_content_type() == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 
        name = part.get_param('name') or 'MyDoc.doc' 
        f = open(name, 'wb') 
        f.write(part.get_payload(None, True))  
        f.close() 
 
        print part.get("content-transfer-encoding") 

请您参考如下方法:

从this table可以清楚地看出(正如您已经得出的结论),该文件是 .xlsx。您不能仅使用 unicode 或 base64 对其进行解码:您需要一个特殊的包。 Excel 文件特别有点诡计(例如 this one 适用于 PowerPoint 和 Word,但不适用于 Excel)。网上有几个,看here - xlrd 可能是最好的。