如何使用python将df更新为现有excel文件

2024-10-02 14:17:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有用于更新已完成电子邮件的现有excel文件。我需要将任何详细信息更新到现有excel。这是我现有的excel文件。它只有如下标题: enter image description here

这是我的输出。它分割了两个excel文件。就像这样

enter image description here

在Excel文件中,它显示如下详细信息:

enter image description here

我希望输出更新现有excel文件的详细信息。像这样:

enter image description here

这是我的python代码:

import os
import pandas as pd
import win32com.client
import time
from datetime import datetime
import openpyxl
today = datetime.today().strftime('%d%m%Y')
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("3.1done_FPA")
finishbox = outlook.GetDefaultFolder(6).Folders.Item("4.finished")
outlook = inbox.Items
mail = outlook.GetLast()

filename = "R:/ReportAFS/PaymentOutlookForm/PaymentOutlookForm_"+str(today)+".xlsx"

for mail in reversed(outlook):
    subject = mail.Subject

    df = pd.read_excel("R:/veerachai/Invoice_form/copy_file/b'"+str(subject)+"'"+"/"+"b'"+str(subject)+"'.xlsm",sheet_name ='PaymentOutlookForm')

    directory = 'R:/ReportAFS/PaymentOutlookForm'
    file = 'PaymentOutlookForm_'+str(today)+'_'+str(subject)+'.xlsx'

    if not os.path.exists(directory):
        os.makedirs(directory)
    df.to_excel(os.path.join(directory, file),index = False)

    time.sleep(1)
    mail.Move(finishbox)
    print(str(mail.Subject)+ ' working success.')

请告诉我如何解决这个问题


Tags: 文件importtodaydatetimeos详细信息mailexcel
1条回答
网友
1楼 · 发布于 2024-10-02 14:17:41

Excel可以很容易地打开和处理.csv文件。您可以将当前Excel文件转换为.csv,然后使用pandas轻松使用它。它提供了带有不同modesto_csv()方法,非常适合您的需要。假设您只想将一行附加到已经存在的.csv,那么您只需调用to_csv()方法,指定a模式参数并将header设置为False(因为我们不希望每次都重新写入头)

df.to_csv('my_csv.csv', mode='a', header=False)

如果您想直接使用Excel文件(无需转换为.csv),可以查看this

相关问题 更多 >

    热门问题