简体   繁体   English

遍历 excel 文件和工作表并在 Python 中连接

[英]Iterate through excel files and sheets and concatenate in Python

Say I have a folder which have multiple excel files with extension xlsx or xls , they share same header column a, b, c, d, e except some empty sheet in several files.假设我有一个文件夹,其中包含多个扩展名为xlsxxls excel 文件,它们共享相同的标题列a, b, c, d, e除了几个文件中的一些空表。

I want to iterate all the files and sheets (except for empty sheets) and concatenate them into one sheet of one file output.xlsx .我想迭代所有文件和工作表(空工作表除外)并将它们连接成一个文件output.xlsx一张纸。

I have iterated through all excel files and append them to one file, but how could I iterate through all the sheets of each files if they have more than one sheets?我已经遍历了所有 excel 文件并将它们附加到一个文件中,但是如果每个文件的所有表都不止一张,我怎么能遍历它们呢?

I need to integrate two block of code below into one.我需要将下面的两个代码块集成为一个。 Thanks for your help.谢谢你的帮助。

import pandas as pd
import numpy as np
import glob

path = os.getcwd()
files = os.listdir(path)
files

df = pd.DataFrame()

# method 1

excel_files = [f for f in files if f[-4:] == 'xlsx' or f[-3:] == 'xls']
excel_files

for f in excel_files:
    data = pd.read_excel(f)
    df = df.append(data)

# method 2

for f in glob.glob("*.xlsx" or "*.xls"):
    data = pd.read_excel(f)
    df = df.append(data, ignore_index=True)

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

For one file to concatenate multiple sheets:对于一个文件连接多个工作表:

file = pd.ExcelFile('file.xlsx')

names = file.sheet_names  # read all sheet names

df = pd.concat([file.parse(name) for name in names])
import pandas as pd

path = os.getcwd()
files = os.listdir(path)
files

excel_files = [file for file in files if '.xls' in file]
excel_files

def create_df_from_excel(file_name):
    file = pd.ExcelFile(file_name)

    names = file.sheet_names

    return pd.concat([file.parse(name) for name in names])

df = pd.concat(
    [create_df_from_excel(xl) for xl in excel_files]
)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM