简体   繁体   中英

Copy Excel tabs (worksheets) from individual xls files to single target xls file using python

I have essentially the converse of the problem answered in Python - Win32com - Open Workbook & Create a New Excel File for Each Tab . I need to iterate recursively thru a set of folders and copy the single tab containing data in a bunch of individual xls files into a single target xls, renaming the tabs appropriately as I go.

I have no formatting or formulae to copy, so nothing fancy needed here. Just first sheet in the individual xls files appended into the target xls.

Thanks in advance for any ideas/snippets.

Suppose there is a folder containing two files and a folder:

  • xls (folder containg excel files)

  • all.xlsx (the aggregated excel file that you are going to copy values to)

  • copy.py (python script to do the work)

For each excel file in the xls folder, only cells A1:C3 in Sheet1 contain values. The python script will copy the values in cells A1:C3 of each individual excel file to the aggreated excel file in a separated sheet and rename it.

import os
from xlwings import Workbook, Sheet, Range

#Get the full paths of the excel files
full_paths = [os.path.abspath(os.path.join('xls', filename)) for filename in os.listdir('xls')]

#Full path of the aggregated excel file
aggregated_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'all.xlsx'))

for number, path in enumerate(full_paths):
    #open the individual excel file
    wb = Workbook(path)
    #Get the values from the individual file
    data = Range('A1').table.value
    wb.close()
    #open the aggregated excel file
    wb = Workbook(aggregated_path)
    #Put the values to the aggregated excel file
    Range('Sheet' + str(number+1), 'A1').value = data
    #Rename the sheet name
    Sheet('Sheet' + str(number+1)).name = str(number+1)

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