首页 > 解决方案 > 如何使用python将df更新为现有的excel文件

问题描述

我有用于更新完成的电子邮件的现有 excel 文件。我需要将任何细节更新到现有的 excel。这是我现有的 excel 文件。它只有这样的标题: 在此处输入图像描述

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

在此处输入图像描述

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

在此处输入图像描述

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

在此处输入图像描述

这是我的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.')

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

标签: python

解决方案


Excel 可以很容易地打开和处理.csv文件。您可以将当前 Excel 文件转换为.csv,然后使用pandas. 它提供了to_csv()不同的方法,modes非常适合您的需要。鉴于您只想将一行附加到一个已经存在的.csv,您可以调用to_csv()指定amode 参数的方法并将其设置headerFalse(因为我们不想每次都重写标题)。

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

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


推荐阅读