【问题标题】:Read from mutiple excel and write to one file从多个excel读取并写入一个文件
【发布时间】:2021-03-16 04:30:24
【问题描述】:

我正在尝试从多个 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,)

【问题讨论】:

  • 请提供预期的MRE - Minimal, Reproducible Example。显示中间结果与预期结果的偏差。我们应该能够将您的代码块粘贴到文件中,运行它并重现您的问题。这也让我们可以在您的上下文中测试任何建议。尤其要明确说明您认为自己缺少什么。
  • files = glob.glob('C:\\Users\\12345\\BOFS\\**\\*.xls',recursive=True)

标签: python python-3.x


【解决方案1】:

Documentation 说:

ExcelWriter 也可用于附加到现有的 Excel 文件:

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

这可能会取代给定的工作表

但您可以使用pd.concat(<dataframes>) 连接数据帧并将所有数据一次写入一张表中。

【讨论】:

    【解决方案2】:

    我测试了这段代码,希望它能在你的情况下工作。

    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() 
    

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 2021-01-23
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      相关资源
      最近更新 更多