Fundamentals 4 min read

How to Automate Excel Data Consolidation with Python: Openpyxl & Pandas Guide

This article walks through automating the aggregation of multiple Excel sheets using Python, presenting two practical solutions—one with openpyxl and another with pandas—complete with code snippets, explanations, and a final tip for sorting results by score.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Automate Excel Data Consolidation with Python: Openpyxl & Pandas Guide

Introduction

Hello, I'm Pipi. This article shares a Python automation task that was asked in a group, focusing on consolidating multiple Excel sheets.

Implementation

First solution uses openpyxl to load workbooks, create a summary sheet, and append rows from sheets whose name ends with “汇总”.

import openpyxl

def append_rows(sheet, rows):
    for row in rows:
        sheet.append(row)

wb = openpyxl.load_workbook('数据测试.xlsx', data_only=True)
sheet_names = wb.sheetnames
new_sheet = wb.create_sheet("全部汇总", 0)
new_sheet.append(['姓名','分数'])
for sheet in sheet_names:
    if sheet.endswith('汇总'):
        book = wb[sheet]
        rows = book.iter_rows(values_only=True, min_row=2, max_col=2)
        append_rows(new_sheet, rows)
wb.save('汇总数据.xlsx')

The second solution leverages pandas to read all summary sheets, concatenate them, and write the combined result.

file = '各种汇总.xlsx'
xlsx_file = pd.ExcelFile(file)
sheet_names = [s for s in xlsx_file.sheet_names if '汇总' in s]
dfs = pd.read_excel(file, sheet_name=sheet_names, usecols=[0,1])
df = pd.concat(dfs).reset_index(drop=True)
df.to_excel('汇总表.xlsx')
print(df)

Optionally, the DataFrame can be sorted by the “成绩” column in descending order:

df = df.sort_values(by='成绩', ascending=False, ignore_index=True)

Conclusion

The provided code demonstrates how to automate Excel data aggregation and ranking using Python, offering two practical approaches with openpyxl and pandas.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

automationdata-processingpandasopenpyxl
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.