如何使用python将来自多个excel文件的数据合并到一个excel文件中?

时间:2018-02-22 15:24:31

标签: python

到目前为止,这是我的代码:

import glob
import pandas as pd
import numpy as np
import openpyxl

log = 'G:\Data\Hotels\hotel.txt'  #text file with my long list of hotels 
file = open(log, 'r')
hotels = []
line = file.readlines()
for a in line:
    hotels.append(a.rstrip('\n'))


for hotel in hotels :
    path = "G:\\Data\\Hotels\\"+hotel+"\\"+hotel+" - Meetings"
    file = hotel+"_Action_Log.xlsx" 
    print(file)

所以到目前为止所有这些代码都打印了我现在要复制的所有酒店文件的名称(字符串我猜?)并将内容粘贴到一个“Master”excel文件中。我只需要每个excel文件中有一个工作表,并且我不需要标题(由于前4行中的花式格式化而放在第5行)。

接下来的步骤是什么?我是python的新手。

1 个答案:

答案 0 :(得分:2)

根据您对问题的描述,我假设您打算将具有相同格式和结构的多个文件打开并附加在一起(即,具有相同的列和列的顺序相同)。

换句话说,你想做这样的事情:

Excel工作表1

Col1 Col2
a    b

Excel工作表2

Col1 Col2
c    d

合并(追加)Excel工作表

Col1 Col2
a    b
c    d

如果我对您的问题的假设是正确的,那么您可以尝试以下方法:

import glob
import pandas as pd
import numpy as np
import openpyxl

# This is your code
log = 'G:\Data\Hotels\hotel.txt'  #text file with my long list of hotels 
file = open(log, 'r')
hotels = []
line = file.readlines()
for a in line:
    hotels.append(a.rstrip('\n'))

# We'll use this list to keep track of all your filepaths
filepaths = []

# I merged your 'path' and 'file' vars into a single variable ('fp')
for hotel in hotels :
    # path = "G:\\Data\\Hotels\\"+hotel+"\\"+hotel+" - Meetings"
    # file = hotel+"_Action_Log.xlsx"
    fp = "G:\\Data\\Hotels\\"+hotel+"\\"+hotel+" -Meetings\\"+hotel+"_Action_Log.xlsx"
    # print(file)
    filepaths.append(fp)

# This list stores all of your worksheets (as dataframes)
worksheets = []

# Open all of your Excel worksheets as Pandas dataframes and store them in 'worksheets' to concatenate later
for filepath in filepaths:
    # You may need to adjust the `skiprows` parameter; right now it's set to skip (not read) the first row of each Excel worksheet (typically the header row)
    df = pd.read_excel(filepath, skiprows=1)
    worksheets.append(df)

# Append all worksheets together
append = pd.concat(worksheets)

# Change 'header' to True if you want to write out column headers
append.to_excel('G:\\Data\\Hotels\\merged.xlsx', header=False)

您可以在此处详细了解pd.concat()方法:https://pandas.pydata.org/pandas-docs/stable/merging.html