将多个xlsx文件合并到一张纸中

时间:2019-01-07 17:04:30

标签: python excel dataframe xlsx merging-data

目前,我正在尝试使用python将多个Excel文件合并为一个。到目前为止,我的情况如下:

sharedDocs = "C:\\SPSharedDocuments\\*.xlsx"
invoices = "C:\\SPInvoices\\*.xlsx"
formsCerts = "C:\\SPForms&Certificates\\*.xlsx"
mgmt = "C:\\SPManagement\\*.xlsx"

files = [sharedDocs, invoices, formsCerts, mgmt]

for docs in files:
    excel = []
    for file in glob.glob(docs):
        excel.append(file)

    excels = [pd.ExcelFile(name) for name in excel]
    frames = [x.parse(x.sheet_names[0], header=None, index_col=None) for x in excels]
    frames_new = [df[1:] for df in frames[1:]]
    combined = pd.concat(frames_new)

    if sharedDocs == docs:
        combined.to_excel("SharedDocsMerged.xlsx", header = False, index = False)
    elif invoices == docs:
        combined.to_excel("InvoicesMerged.xlsx", header = False, index = False)
    elif formsCerts == docs:
        combined.to_excel("FormsCertsMerged.xlsx", header = False, index = False)
    else:
        combined.to_excel("MGMTMerged.xlsx", header = False, index = False)

这有效,但是它不会复制第一个标题,因此我知道每列的名称是什么。在我将frames_new = [df[1:] for df in frames[1:]]读为frames[1:] = [df[1:] for df in frames[1:]]的行之前,但这导致同一文件的多个副本。

我所需要的就是复制一个标头,这样我就知道每一列的值。

非常感谢您的帮助。

更新:

我尝试使用下面的帖子暗示这是一个类似的问题,并且我编辑了代码,使其看起来像这样:

sharedDocs = "C:\\SPSharedDocuments\\*.xlsx"
invoices = "C:\\SPInvoices\\*.xlsx"
formsCerts = "C:\\SPForms&Certificates\\*.xlsx"
mgmt = "C:\\SPManagement\\*.xlsx"

files = [sharedDocs, invoices, formsCerts, mgmt]

for docs in files:
    excel = []
    for file in glob.glob(docs):
        excel.append(pd.read_excel(file))
    df = pd.concat(excel, ignore_index=True, sort = True)

    if sharedDocs == docs:
        df.to_excel("SharedDocsMerged.xlsx", header = False, index = False)
    elif invoices == docs:
        df.to_excel("InvoicesMerged.xlsx", header = False, index = False)
    elif formsCerts == docs:
        df.to_excel("FormsCertsMerged.xlsx", header = False, index = False)
    else:
        df.to_excel("MGMTMerged.xlsx", header = False, index = False)

我得到的结果是在左侧增加了2列,缺少了列,仍然没有标题。

0 个答案:

没有答案