簡體   English   中英

Append 新數據到現有 excel 文件 pandas python

[英]Append new data into existing excel file pandas python

大家好,我正在嘗試將新數據(列和值)添加到現有的 excel 電子表格中。 我將 Order_Sheet.xlsx 保存為這樣的數據:

 Item:         Quantity:      Price: 
disposable cups   7000         $0.04

並從 spreadsheet_1.xlsx 添加此信息

  Order Number    Location    Date
 0 A-21-897274     Ohio        07/01/2022

將它們添加到現有的 excel 工作表 Order_Sheet.xlsx 而不是創建新的 excel。這樣它看起來像:

 Item:         Quantity:      Price:   Order Number:    Location:    Date:
 disposable cups   7000         $0.04   A-21-897274      Ohio     07/01/2022

有沒有一種簡單的方法可以將 append 新數據添加到現有的 excel 或者可能合並兩個 excel 文件?

僅適用於 pandas 1.4+。 以下代碼假定行的順序在第一次和第二次寫入之間是相同的。 它還假定您確切知道現有列的數量。

import pandas as  pd


df2 = pd.DataFrame({"c": [3, 5], "d": [8, 9]})
df3 = pd.DataFrame({"c": [9, 10], "d": [-1, -9]})
df4 = pd.DataFrame({"a": [1, 2], "b": [3, 4]})

with pd.ExcelWriter('./Order_List.xlsx', mode='w') as writer:
    df2.to_excel(writer, index=False)

with pd.ExcelWriter('./Order_List.xlsx', mode="a", if_sheet_exists="overlay") as writer:
    df3.to_excel(writer, startrow=3, header=False, index=False)
    df4.to_excel(writer, startrow=0, startcol=2, header=True, index=False)

鏈接到1.4 文檔

我在文檔中找到了這個。

  {storage_options}
        .. versionadded:: 1.2.0
    if_sheet_exists : {{'error', 'new', 'replace', 'overlay'}}, default 'error'
        How to behave when trying to write to a sheet that already
        exists (append mode only).
        * error: raise a ValueError.
        * new: Create a new sheet, with a name determined by the engine.
        * replace: Delete the contents of the sheet before writing to it.
        * overlay: Write contents to the existing sheet without removing the old
          contents.
        .. versionadded:: 1.3.0

這是完整的鏈接: https://github.com/pandas-dev/pandas/blob/main/pandas/io/excel/_base.py#L800-L814

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM