如何将多个工作表写入一个新的excel,而不互相覆盖?

How to write multiple sheets into a new excel, without overwriting each other?

我正在尝试将多个 excel 的 A 列写入新的 excel 的 A 列(假设所有 excel 都有一个作品sheet 每个。)我写了一些代码,可以将一个excel的A列写入新的excel的A列;但是如果有多个excel,新的excel的A列会被覆盖多次。那么,我如何才能将所有列 As 一个接一个地添加到新的 excel sheet 而不会相互覆盖呢? 以下是我的代码:

import os, openpyxl

path = os.getcwd()

def func(file):
    for file in os.listdir(path):
        if file.endswith('.xlsx'):
            wb = openpyxl.load_workbook(file)
            sheet = wb.active
            colA = sheet['A']
            wb = openpyxl.Workbook()
            r = 1
            for i in colA:
                sheet = wb.active       
                sheet.cell(row=r, column=1).value = i.value
                r += 1
                wb.save('new.xlsx')
func(file)

非常感谢!!

你可以继续,例如:

import os, openpyxl

path = os.getcwd()


def func(outputFile):
    c = 0

    #create output workbook
    wbOut = openpyxl.Workbook()
    sheetOut = wbOut.active

    for fName in os.listdir(path):
        if fName.endswith('.xlsx'):
            c += 1 #move to the next column in output

            wb = openpyxl.load_workbook(fName)
            sheet = wb.active #input sheet

            #for r in range(1, sheet.max_row+1):
            #    sheetOut.cell(row=r, column=c).value = sheet.cell(row = r, column = 1).value

            for r, cell in enumerate(sheet['A']):
                sheetOut.cell(row = r+1, column = c).value = cell.value

    wbOut.save(outputFile)

#"concatenate" all columns A into one single column
def funcAppend(outputFile):
    wbOut = openpyxl.Workbook()
    sheetOut = wbOut.active

    r = 1
    for fName in os.listdir(path):
        if fName.endswith('.xlsx'):
            wb = openpyxl.load_workbook(fName)
            sheet = wb.active

            for cell in sheet['A']:
                sheetOut.cell(row = r, column = 1).value = cell.value
                r += 1
    wbOut.save(outputFile)

func('test.xlsx')