如何将多张表格写入新的Excel中,而不会互相覆盖?

时间:2017-03-06 08:32:57

标签: python excel openpyxl

我试图写多个excels'列A进入一个新的excel的列A(假设所有excel都有一个工作表。)我已经编写了一些代码,可以将一个excel的A列写入新的excel'列A;但如果有多个excel,新的excel的A列将被多次覆盖。那么我怎么能一个接一个地将所有列As添加到新的excel表中而不会互相覆盖呢? 以下是我的代码:

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)

非常感谢!!

1 个答案:

答案 0 :(得分:1)

你可以举例如:

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')