下一行不能使用xlsxwriter在excel文件上写

时间:2019-10-16 17:25:17

标签: excel python-3.x

我想将所有数字保存在下一行的主题中,但只保存1行。打印它们时仍显示“数字”,但是excel文件(1.xlsx)仅将第一个数字保存在A1

def read_email_from_gmail():
        workbook = xlsxwriter.Workbook('1.xlsx') 
        worksheet = workbook.add_worksheet() 
        column = 0
        row = 0
        mail = imaplib.IMAP4_SSL('imap.yandex.com')
        mail.login('myemail','password')
        mail.select('inbox')

        result, data = mail.search(None, 'SUBJECT "New"')
        mail_ids = data[0]

        id_list = mail_ids.split()   
        first_email_id = int(id_list[0])
        latest_email_id = int(id_list[-1])

        for i in range(latest_email_id,first_email_id, -1):
            # need str(i)
            result, data = mail.fetch(str(i), '(RFC822)' )
            for response_part in data:
                if isinstance(response_part, tuple):
                    # from_bytes, not from_string
                    msg = email.message_from_bytes(response_part[1])
                    email_subject = msg['subject']
                    if (email_subject.find('#') != -1): 
                        number = email_subject.split("#")[1]
                        worksheet.write(row, column, number)
                        row += 1
                        workbook.close()
                    else: 
                        print ("no have Number") 
                    email_from = msg['from']
                    print ('From : ' + email_from + '\n')
                    print ('Subject : ' + email_subject + '\n')
                    print ('Number : ' + number + '\n')


# nothing to print here
read_email_from_gmail()

1 个答案:

答案 0 :(得分:0)

程序在写入xlsx文件后立即关闭它:

                    if (email_subject.find('#') != -1): 
                        number = email_subject.split("#")[1]
                        worksheet.write(row, column, number)
                        row += 1
                        workbook.close()

您应将close()从循环中移到使用xlsxwriter.Workbook()创建文件的同一级别。