0

目前我正在尝试使用 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 个额外的列,缺少一个列并且仍然没有标题。

4

0 回答 0