簡體   English   中英

Python: How to copy Excel worksheet from multiple Excel files to one Excel file that contains all the worksheets from other Excel files

[英]Python: How to copy Excel worksheet from multiple Excel files to one Excel file that contains all the worksheets from other Excel files

It's my first time to use pandas, I have multiple excel files, that i want to combine all into one Excel file using python pandas.

我設法將每個 excel 文件中第一張紙的內容合並到一個新 excel 文件中的一張紙中,如下圖所示:一張紙中的組合紙

我寫了這段代碼來實現這個:

import glob
import pandas as pd
path = "C:/folder"
file_identifier = "*.xls"
all_data = pd.DataFrame()
for f in glob.glob(path + "/*" + file_identifier):
   df = pd.read_excel(f)
   all_data = all_data.append(df,ignore_index=True)

writer = pd.ExcelWriter('combined.xls', engine='xlsxwriter')    
all_data.to_excel(writer, sheet_name='Summary Sheet') 
writer.save()
file_df = pd.read_excel("C:/folder/combined.xls")
# Keep only FIRST record from set of duplicates
file_df_first_record = file_df.drop_duplicates(subset=["Test summary", "Unnamed: 1", "Unnamed: 2", 
"Unnamed: 3"], keep="first")
file_df_first_record.to_excel("filtered.xls", index=False, sheet_name='Summary Sheet')

但我有兩個問題:

  1. 如何刪除具有“未命名”的單元格,如上圖所示
  2. 如何從所有其他 Excel 文件中復制其他工作表(每個 Excel 文件中的第二個工作表,而不是第一個工作表),並將其放入一個 Excel 文件中,如在多個圖片中顯示的學生姓名和學生姓名。

一個 excel 文件中的所有工作表

So i managed to combine worksheet1 from all Excel files in one sheet, but now I want to copy A, B, C, D, E worksheets into one Excel file that has all other remaining worksheets in other Excel files.

我擁有的每個 Excel 文件看起來像這個單個 excel 文件

如果您想將所有數據收集在一個工作表中,您可以使用以下腳本:

  1. 將所有要處理的excel工作簿(即excel文件)放入一個文件夾(見變量paths )。

  2. 使用glob.glob獲取該文件夾中所有工作簿的路徑。

  3. 使用read_excel(path, sheet_name=None)返回每個工作簿的所有工作表並准備合並。

  4. 使用concat合並所有工作表。

  5. 導出最終的 output to_excel

     import pandas as pd import glob paths = glob.glob(r"C:\excelfiles\*.xlsx") path_save = r"finished.xlsx" df_lst = [pd.read_excel(path, sheet_name=None).values() for path in paths] df_lst = [y.transpose().reset_index().transpose() for x in df_lst for y in x] df_result = pd.concat(df_lst, ignore_index=True) df_result.to_excel(path_save, index=False, header=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM