[英]Copy the data from specific files and pate it in master file on a specific sheet
[英]Copy Data from multiple excel files to existing file on specific sheet
我想从多个 excel 文件中复制数据并将其粘贴到现有的 excel 文件中。
import os
import openpyxl
import pandas as pd
my_path = r'C://Users//greencolor//Autoreport//Load_attachments//' # Updating every monday with new files
my_path1 =r'C://Users//greencolor//Desktop//Autoreport//' # place of Master.xlsx
for filename in os.listdir(my_path): #loop though the downloaded files
if filename.startswith('PB orders Dec'): #finds the file with the name PB orders December.xlsb
dec = pd.read_excel(os.path.join(my_path, filename),
sheet_name='Raw data ',
engine='pyxlsb') #reading the specific sheet named Raw data
with pd.ExcelWriter(my_path1 + '//Maaster.xlsx', mode='a', engine=openpyxl) as writer:
dec.to_excel(writer, sheet_name='DecData', index=False) #copyes the data from PB orders December.xlsb and paste it in Master file on sheet Decdata without deleting other sheets. Basically updating all data with new data.
我的问题是我想对多个文件执行上述相同的操作。 例如,如果在Load_attachments
中是名为 PB 订单 November.xlsb 的文件,我想将相同的代码应用于该 11 月文件,等等任何月份名称文件。
您可以将整个内容(减去导入)放在一个 for 循环中,并为其提供文件名开头的数组:
import os
import openpyxl
import pandas as pd
fnamebegin_array = ['PB orders Jan','PB orders Feb','PB orders Mar','etc']
sheetname_array = ['JanData','FebData','MarData','etc']
for i in range(len(fnamebegin_array)): # would be 12, if there is data for each month in a year
my_path = r'C://Users//greencolor//Autoreport//Load_attachments//'
my_path1 =r'C://Users//greencolor//Desktop//Autoreport//'
for filename in os.listdir(my_path):
if filename.startswith(fnamebegin_array[i]):
month = pd.read_excel(os.path.join(my_path, filename),
sheet_name='Raw data ',
engine='pyxlsb')
with pd.ExcelWriter(my_path1 + '//Master.xlsx', mode='a', engine=openpyxl) as writer:
month.to_excel(writer, sheet_name=sheetname_array[i], index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.