从python中的.eml文件解析Excel附件

时间:2019-01-07 16:08:19

标签: python excel attachment

我正在尝试解析.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

问题是

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

enter image description here

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

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")

2 个答案:

答案 0 :(得分:1)

this table中可以清楚地看出(并且您已经得出结论),该文件是.xlsx。您不能仅使用unicodebase64对其进行解码:您需要一个特殊的程序包。 Excel文件特别容易欺骗(例如this one可以使用PowerPoint和Word,但不能使用Excel)。在线上有一些,请参见here-xlrd可能是最好的。

答案 1 :(得分:0)

这是我的解决方法:

我发现了2件事:

1。)我以为.open()进入了.eml并更改了选定的解码元素。我以为我需要在前进之前先查看解码后的数据。 .open()真正发生的是在.xlsx文件的同一目录中创建一个新文件。必须先打开附件,然后才能处理数据。 2.)您必须打开带有文件路径的xlrd工作簿。

import email
import xlrd 

data = file('EmailFileName.eml').read()
    msg = email.message_from_string(data)  # entire message

    if msg.is_multipart():
        for payload in msg.get_payload():
            bdy = payload.get_payload()
    else:
        bdy = msg.get_payload()

    attachment = msg.get_payload()[1]


    # open and save excel file to disk
    f = open('excelFile.xlsx', 'wb')
    f.write(attachment.get_payload(decode=True))
    f.close()

    xls = xlrd.open_workbook(excelFilePath) # so something in quotes like '/Users/mymac/thisProjectsFolder/excelFileName.xlsx'

    # Here's a bonus for how to start accessing excel cells and rows
    for sheets in xls.sheets():
        list = []
        for rows in range(sheets.nrows):
            for col in range(sheets.ncols):
                list.append(str(sheets.cell(rows, col).value))