简体   繁体   中英

How can I add an existing workbook sheet to another existing workbook with openpyxl?

I am trying to create an new excel that contains the first sheet of a list of excel files.

I tried the following but of course line wb.create_sheet(sheet) doesn't work.

wb = Workbook('new.xlsx')

for i in range(len(file_list)):
    excel = load_workbook(file_list[i], read_only=False)
    sheet = excel[excel.sheetnames[0]]
    sheet.Name = tab_names_list[i]

    wb.create_sheet(sheet)


wb.save('new.xlsx')

At the same time replacing wb.create_sheet(sheet) with wb.copy_worksheet(sheet) gives the error ValueError: Cannot copy worksheets in read-only or write-only mode

This may not work for you but this is what I use in a similar application. It does require pandas dataframes, I'm not sure if you're using them or not.

file_list = [file_1, file_2]
sheet_names = ['file1_name', 'file2_name']

writer = pd.ExcelWriter("workbook_name.xlsx", engine='xlsxwriter')

for file, s_names in zip(file_list, sheet_names):
    file.to_excel(writer, sheet_name=s_names)
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