Skip to main content
 首页 » 编程设计

python之如何使用 Python 将每个 Excel 工作表中的数据复制并粘贴到最终工作表中

2024年11月24日9www_RR

我在一个工作簿中有 7 个 Excel 工作表,我正在尝试将每个 Excel 工作表中的数据复制并粘贴到我的最终工作表中。下面的代码创建了名为“Final Sheet”的最终工作表,但不复制每张工作表中的任何数据。我需要一个循环来遍历每张纸并将数据复制并粘贴到最后一张纸中,但不知道该怎么做。

工作表 1 = 北美,工作表 2 = 日本,工作表 3 = 中国等

`#create final list sheet 
 open = openpyxl.load_workbook(filepath) 
 ws2 = open.create_sheet('Final List') # this creates the final sheet 
 open.save(filepath)` 
 
`#put data into final list 
 wb = openpyxl.load_workbook(filepath) 
 sheet1 = open.get_sheet_by_name('North America') 
 finalListSheet = open.get_sheet_by_name('Final List') 
 wb.save(filepath)` 

请您参考如下方法:

此处提出了类似的问题:Python Loop through Excel sheets, place into one df

我在这里简化了这个。此方法使用 Pandas:

import pandas as pd 
 
sheets_dict = pd.read_excel(filepath, sheetname=None) 
 
full_table = pd.DataFrame() 
 
//Loop in sheets 
for name, sheet in sheets_dict.items(): 
    sheet['sheet'] = name 
    full_table = full_table.append(sheet) 
 
//Need to save the DF in your Final Sheet 

这是关于如何在特定 Excel 工作表中保存数据框 (DF) 的另一个问题:Pandas Dataframe to excel sheet