简体   繁体   中英

Moving sheets from excel files into one workbook using openpyxl

So I've been trying to code a script which loads all excel files from a specific location and moves worksheets inside these files into one workbook. I'm ending with and error:

AttributeError: 'DataFrame' object has no attribute 'DataFrame' .

I'm pretty new to this so I would really appreciate any tip on how to make that work. I can stick only with openpyxl because at the moment I cannot install xlrd module on my workstation.

from pandas import ExcelWriter
import glob
import pandas as pd
import openpyxl

writer = ExcelWriter("output.xlsx")
for filename in glob.glob (r"C:\path\*.xlsx"):
    wb = openpyxl.load_workbook(filename)
    for ws in wb.sheetnames:
        ws = wb[ws]
        print (ws)
        data = ws.values
        columns = next(data)[0:]
        df= pd.DataFrame(data, columns=columns)
        print(df)
        for df in df.DataFrame:
            df.to_excel([writer,sheet_name= ws)

writer.save()

first you have to use sheet_name as a string not an object and another thing is last for loop is not needed as we loop through sheet names.

from pandas import ExcelWriter
import glob
import pandas as pd
import openpyxl


writer = ExcelWriter("output.xlsx")
for filename in glob.glob (r"C:\path\*.xlsx"):
    wb = openpyxl.load_workbook(filename)
    for ws in wb.sheetnames:
        ws1 = wb[ws]
        data = ws1.values
        columns = next(data)[0:]
        df= pd.DataFrame(data, columns=columns)
        df.to_excel(writer,sheet_name=ws,index = False)

writer.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM