[英]How to merge multiple XLSX files into one Workbook while keeping their worksheets separate?
I'm trying to merge all.xlsx files within a folder into one workbook while keeping their worksheets separated.我正在尝试将文件夹中的所有.xlsx 文件合并到一个工作簿中,同时保持它们的工作表分开。 My code below is grabbing specified files, merging them into one workbook but only copying the first worksheet from each file instead of all their worksheets.
我下面的代码是抓取指定的文件,将它们合并到一个工作簿中,但只复制每个文件中的第一个工作表,而不是所有工作表。
My output file is currently one workbook containing the first worksheet of each merged file but some files have multiple worksheets.我的 output 文件目前是一个工作簿,其中包含每个合并文件的第一个工作表,但有些文件有多个工作表。 Would anyone know how I can grab all worksheets from multiple files and combine them into one workbook?
有谁知道我如何从多个文件中获取所有工作表并将它们合并到一个工作簿中?
Thanks for your time!谢谢你的时间!
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
path = r'C:\Users\Desktop\merge'
files = os.listdir(path)
for f in [os.path.join(os.getcwd(), "Daily Pipeline"), os.path.join(os.getcwd(), "Loans")]:
w = excel.Workbooks.Open(f)
w.Sheets(1).Copy(wb.Sheets(1))
wb.SaveAs(os.path.join(os.getcwd(), "Final.xlsx"))
excel.Application.Quit()
Why dont you try reading the excel files using python pandas?为什么不尝试使用 python pandas 读取 excel 文件? You could use glob to read the files from your directory and then merge them into a dataframe.
您可以使用 glob 从目录中读取文件,然后将它们合并到 dataframe 中。
import glob
all_data = pd.DataFrame()
path = 'd:/projects/chassis/data/*.xlsx'
for f in glob.glob(path):
df = pd.read_excel(f, sheet_name=None, ignore_index=True, skiprows=6, usecols=8)
cdf = pd.concat(df.values())
all_data = all_data.append(cdf,ignore_index=True)
print(all_data)
This might do the work!这可能会起作用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.