python - 如何使用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.')
请告诉我如何解决这个问题。
解决方案
Excel 可以很容易地打开和处理.csv
文件。您可以将当前 Excel 文件转换为.csv
,然后使用pandas
. 它提供了to_csv()
不同的方法,modes
非常适合您的需要。鉴于您只想将一行附加到一个已经存在的.csv
,您可以调用to_csv()
指定a
mode 参数的方法并将其设置header
为False
(因为我们不想每次都重写标题)。
df.to_csv('my_csv.csv', mode='a', header=False)
如果您想直接使用 Excel 文件(不转换为.csv
),可以查看此.
推荐阅读
- laravel - Laravel Eloquent Eager Load with Sums
- python - python : 引用不同的 pip 目录
- git - 使用 Jenkins Pipeline 更改电子邮件 git
- java - 如何在 Groovy 中使用断言包含
- google-chrome-extension - SignalR 集线器未在 Edge 中加载以进行扩展
- python - Pandas 为列表字典中的每个字符串创建虚拟特征
- qt - QOAuth2AuthorizationCodeFlow 访问 Spotify
- scala - scala.math.BigInt 不能转换为 java.lang.Long
- ffmpeg - libavformat 在编码时生成没有大小的 flv 文件
- javascript - 如何将所有 CSS 样式从一个 DOM 复制到另一个?