简体   繁体   English

使用python将Excel选项卡(工作表)从单个xls文件复制到单个目标xls文件

[英]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 . 我本质上是在Python-Win32com-打开工作簿并为每个选项卡创建新的Excel文件中回答的问题的。 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. 我需要通过一组文件夹进行递归迭代,并将包含单个xls文件中的数据的单个选项卡复制到单个目标xls中,并在我进行操作时适当地重命名这些选项卡。

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. 仅将单个xls文件中的第一张表附加到目标xls中。

Thanks in advance for any ideas/snippets. 预先感谢您的任何想法/摘要。

Suppose there is a folder containing two files and a folder: 假设有一个包含两个文件的文件夹和一个文件夹:

  • xls (folder containg excel files) xls(包含Excel文件的文件夹)

  • all.xlsx (the aggregated excel file that you are going to copy values to) all.xlsx(要将值复制到的聚合excel文件)

  • copy.py (python script to do the work) copy.py(执行Python脚本的工作)

For each excel file in the xls folder, only cells A1:C3 in Sheet1 contain values. 对于xls文件夹中的每个excel文件,仅Sheet1中的单元格A1:C3包含值。 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. python脚本会将每个单独excel文件的单元格A1:C3中的值复制到单独工作表中的已合并excel文件中,然后重命名。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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