[英]Adding Multiple .xls files to a Single .xls file, using the file name to name tabs
[英]Copy Excel tabs (worksheets) from individual xls files to single target xls file using python
我本質上是在Python-Win32com-打開工作簿並為每個選項卡創建新的Excel文件中回答的問題的。 我需要通過一組文件夾進行遞歸迭代,並將包含單個xls文件中的數據的單個選項卡復制到單個目標xls中,並在我進行操作時適當地重命名這些選項卡。
我沒有要復制的格式或公式,因此這里不需要花哨的東西。 僅將單個xls文件中的第一張表附加到目標xls中。
預先感謝您的任何想法/摘要。
假設有一個包含兩個文件的文件夾和一個文件夾:
xls(包含Excel文件的文件夾)
all.xlsx(要將值復制到的聚合excel文件)
對於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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.