簡體   English   中英

從多個 excel 讀取並寫入一個文件

[英]Read from mutiple excel and write to one file

我正在嘗試從多個 xls 文件中讀取數據並將其寫入一個文件。

我下面的代碼只寫第一個文件。 不知道我錯過了什么。

import glob import os import pandas as pd


def list_files(dir):
    r = []
    for root, dirs, files in os.walk(dir):
        for name in files:
            r.append(os.path.join(root, name))
    return r  

files = list_files("C:\\Users\\12345\\BOFS")

for file in files:
    df = pd.read_excel(file)
    new_header = df.iloc[1]
    df = df[2:]
    df.columns = new_header  
   
     with pd.ExcelWriter("C:\\Users\\12345\\Test\\Test.xls", mode='a') as writer:
        df.to_excel(writer,index=False, header=True,)

文檔說:

ExcelWriter 也可用於 append 到現有 Excel 文件:

 with pd.ExcelWriter('output.xlsx', mode='a') as writer: df.to_excel(writer, sheet_name='Sheet_name_3')

這可能會取代給定的工作表

但是您可以使用pd.concat(<dataframes>)連接數據幀並將所有數據一次寫入一張紙。

我測試了這段代碼,希望它能在你的情況下工作。

import glob, os
os.chdir("D:/Data Science/stackoverflow")
for file in glob.glob("*.xlsx"):
  df = pd.read_excel(file)
  all_data = all_data.append(df,ignore_index=True)

# now save the data frame
writer = pd.ExcelWriter('output.xlsx')
all_data.to_excel(writer,'sheet1')
writer.save() 

暫無
暫無

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

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