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

时间:2015-03-25 15:33:20

标签: python excel

我基本上与Python - Win32com - Open Workbook & Create a New Excel File for Each Tab中回答的问题相反。我需要通过一组文件夹递归迭代,并将包含一堆单个xls文件中的数据的单个选项卡复制到单个目标xls中,然后在我去的时候适当地重命名选项卡。

我没有要复制的格式或公式,因此这里不需要任何花哨的东西。只是将第一张单独的xls文件附加到目标xls中。

提前感谢任何想法/片段。

1 个答案:

答案 0 :(得分:0)

假设有一个包含两个文件和一个文件夹的文件夹:

  • xls(包含excel文件的文件夹)

  • all.xlsx(您要复制的聚合excel文件 值)

  • copy.py(用于完成工作的python脚本)

对于xls文件夹中的每个excel文件,Sheet1中只有单元格A1:C3包含值。 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)