使用Python實(shí)現(xiàn)Excel文件的拆分與合并操作
準(zhǔn)備工作
在開始之前,需要安裝幾個(gè)必要的Python庫:
pandas:用于數(shù)據(jù)處理和分析openpyxl:用于讀寫Excel文件
可以通過以下命令安裝這些庫:
pip install pandas openpyxl
使用Python拆分Excel文件
拆分單個(gè)工作表
假設(shè)有一個(gè)包含多行數(shù)據(jù)的Excel文件,需要將其拆分成多個(gè)較小的文件。以下是一個(gè)示例代碼,演示如何將單個(gè)工作表按行拆分成多個(gè)文件。
import pandas as pd
def split_excel_by_rows(file_path, rows_per_file, output_prefix):
# 讀取Excel文件
df = pd.read_excel(file_path)
# 計(jì)算總行數(shù)
total_rows = len(df)
# 計(jì)算需要拆分的文件數(shù)量
num_files = (total_rows // rows_per_file) + (1 if total_rows % rows_per_file != 0 else 0)
for i in range(num_files):
start_row = i * rows_per_file
end_row = (i + 1) * rows_per_file
split_df = df.iloc[start_row:end_row]
# 保存拆分后的文件
output_file = f"{output_prefix}_{i+1}.xlsx"
split_df.to_excel(output_file, index=False)
print(f"文件 {output_file} 已保存")
# 示例使用
split_excel_by_rows('data.xlsx', 100, 'split_data')拆分多個(gè)工作表
如果Excel文件包含多個(gè)工作表,可以按工作表拆分文件。
import pandas as pd
def split_excel_by_sheets(file_path, output_prefix):
# 讀取Excel文件
xls = pd.ExcelFile(file_path)
for sheet_name in xls.sheet_names:
df = pd.read_excel(file_path, sheet_name=sheet_name)
output_file = f"{output_prefix}_{sheet_name}.xlsx"
df.to_excel(output_file, index=False)
print(f"工作表 {sheet_name} 已拆分為文件 {output_file}")
# 示例使用
split_excel_by_sheets('data_with_sheets.xlsx', 'split_data')使用Python合并Excel文件
合并多個(gè)工作表到一個(gè)文件
有時(shí)候,需要將多個(gè)Excel文件合并成一個(gè)文件中的多個(gè)工作表。
以下是示例代碼:
import pandas as pd
def merge_excels_to_sheets(file_list, output_file):
with pd.ExcelWriter(output_file) as writer:
for file in file_list:
df = pd.read_excel(file)
sheet_name = file.split('.')[0]
df.to_excel(writer, sheet_name=sheet_name, index=False)
print(f"文件 {file} 已合并到 {output_file} 的工作表 {sheet_name}")
# 示例使用
files_to_merge = ['data1.xlsx', 'data2.xlsx', 'data3.xlsx']
merge_excels_to_sheets(files_to_merge, 'merged_data.xlsx')合并多個(gè)文件到一個(gè)工作表
另外一種常見需求是將多個(gè)Excel文件的數(shù)據(jù)合并到一個(gè)文件的同一個(gè)工作表中。
import pandas as pd
def merge_excels_to_one_sheet(file_list, output_file):
merged_df = pd.DataFrame()
for file in file_list:
df = pd.read_excel(file)
merged_df = pd.concat([merged_df, df], ignore_index=True)
print(f"文件 {file} 的數(shù)據(jù)已合并")
merged_df.to_excel(output_file, index=False)
print(f"所有文件已合并到 {output_file}")
# 示例使用
files_to_merge = ['data1.xlsx', 'data2.xlsx', 'data3.xlsx']
merge_excels_to_one_sheet(files_to_merge, 'merged_data.xlsx')綜合示例:拆分并合并Excel文件
假設(shè)需要先將一個(gè)大Excel文件拆分為多個(gè)小文件,然后再將這些小文件合并成一個(gè)新的文件。
以下是實(shí)現(xiàn)這個(gè)過程的完整代碼:
import pandas as pd
def split_excel_by_rows(file_path, rows_per_file, output_prefix):
df = pd.read_excel(file_path)
total_rows = len(df)
num_files = (total_rows // rows_per_file) + (1 if total_rows % rows_per_file != 0 else 0)
for i in range(num_files):
start_row = i * rows_per_file
end_row = (i + 1) * rows_per_file
split_df = df.iloc[start_row:end_row]
output_file = f"{output_prefix}_{i+1}.xlsx"
split_df.to_excel(output_file, index=False)
print(f"文件 {output_file} 已保存")
def merge_excels_to_one_sheet(file_list, output_file):
merged_df = pd.DataFrame()
for file in file_list:
df = pd.read_excel(file)
merged_df = pd.concat([merged_df, df], ignore_index=True)
print(f"文件 {file} 的數(shù)據(jù)已合并")
merged_df.to_excel(output_file, index=False)
print(f"所有文件已合并到 {output_file}")
# 示例使用
# 拆分大文件
split_excel_by_rows('data.xlsx', 100, 'split_data')
# 假設(shè)我們已經(jīng)將文件拆分成了多個(gè)文件
split_files = ['split_data_1.xlsx', 'split_data_2.xlsx', 'split_data_3.xlsx']
# 合并拆分后的文件
merge_excels_to_one_sheet(split_files, 'final_merged_data.xlsx')總結(jié)
本文詳細(xì)介紹了如何使用Python實(shí)現(xiàn)Excel文件的拆分與合并操作。通過使用pandas和openpyxl庫,我們可以方便地讀取、處理和保存Excel文件。文章展示了如何按行拆分單個(gè)工作表、按工作表拆分文件,以及將多個(gè)文件合并到一個(gè)文件中的多個(gè)工作表或同一個(gè)工作表中。具體示例包括將一個(gè)大Excel文件按行拆分成多個(gè)較小文件,并將這些小文件合并成一個(gè)新的文件。通過這些示例,可以掌握在實(shí)際工作中高效處理Excel文件的方法。這些技巧可以幫助大家簡化數(shù)據(jù)處理流程,提高工作效率。
以上就是使用Python實(shí)現(xiàn)Excel文件的拆分與合并操作的詳細(xì)內(nèi)容,更多關(guān)于Python Excel拆分與合并的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python異步發(fā)送日志到遠(yuǎn)程服務(wù)器詳情
這篇文章主要介紹了Python異步發(fā)送日志到遠(yuǎn)程服務(wù)器詳情,文章通過簡單輸出到cmd和文件中的代碼展開詳情,需要的朋友可以參考一下2022-07-07
Python3.4 tkinter,PIL圖片轉(zhuǎn)換
我們給大家整理了關(guān)于Python3.4 tkinter,PIL圖片轉(zhuǎn)換的相關(guān)完整代碼,大家可以學(xué)習(xí)測試下。2018-06-06
Python實(shí)現(xiàn)SICP賦值和局部狀態(tài)
這篇文章主要介紹了Python實(shí)現(xiàn)SICP 賦值和局部狀態(tài)的相關(guān)知識,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03
python并行設(shè)計(jì)的實(shí)現(xiàn)
python中的并行設(shè)計(jì)可以顯著增強(qiáng)程序處理大量數(shù)據(jù)或復(fù)雜計(jì)算的速度,通過使用threading、multiprocessing和concurrent.futures等庫,開發(fā)者可以有效利用多核CPU的計(jì)算力,下面就來詳細(xì)的介紹一下2024-09-09
對python 合并 累加兩個(gè)dict的實(shí)例詳解
今天小編就為大家分享一篇對python 合并 累加兩個(gè)dict的實(shí)例詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
ConvNeXt實(shí)戰(zhàn)之實(shí)現(xiàn)植物幼苗分類
ConvNeXts由標(biāo)準(zhǔn)ConvNet模塊構(gòu)建,在準(zhǔn)確性和可擴(kuò)展性方面與 Transformer競爭,實(shí)現(xiàn)87.8% ImageNet top-1 準(zhǔn)確率,在 COCO 檢測和 ADE20K 分割方面優(yōu)于 Swin Transformers。本文將利用ConvNeXt實(shí)現(xiàn)植物幼苗分類,需要的可以參考一下2022-01-01
Python?matplotlib繪圖時(shí)指定圖像大小及放大圖像詳解
Matplotlib是一個(gè)面向?qū)ο蟮睦L圖庫,我們繪制的圖像中,每條曲線,每個(gè)邊框等等都對應(yīng)一個(gè)對象,下面這篇文章主要給大家介紹了關(guān)于Python?matplotlib繪圖時(shí)指定圖像大小及放大圖像的相關(guān)資料,需要的朋友可以參考下2022-05-05
PyQt5使用QTimer實(shí)現(xiàn)電子時(shí)鐘
這篇文章主要為大家詳細(xì)介紹了PyQt5使用QTimer實(shí)現(xiàn)電子時(shí)鐘,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07

