利用python批量读取大量Excel表格文件中指定内容并汇总

工作中出现需要从大量Excel表格文件中读取指定单元格内容并汇总到一个表格中。上网搜索一下,利用Python的pandas模块可以快速实现。openpyxl也可以,不过为了快速,以能搜到的形成代码为优先。

简单修改别人代码,实现如下。

python 复制代码
import os
import pandas as pd

or_path = "D:/xlsx"
re_path = "D:/results"

result_df = pd.DataFrame()

# 因为这个例子里,Excel文件独立在不同文件夹中,所以需要遍历所有子目录
for root, dirs, files in os.walk(or_path):
    for file in files:
        # 只处理指定文件
        if !file.endswith(".xlsx"):
            continue

        read_xls = pd.ExcelFile(os.path.join(root, file))

        # 例子中,每个文件有多个sheet,需要遍历每个sheet
        for sheetname in read_xls.sheet_name:
            # 通过sheet名字读取表格内容
            df = read_xls.parse(sheetname, header=None)
            # 通过values函数可以读取单元格内容
            # 通过Data函数可以构建表格
            read_df = pd.Data({'name':[df.values[2, 1]], 'age':[df.values[3, 1]]})

            # 拼接表格
            result_df = pd.concat([result_df, read_df])

# 输出汇总到文件
result_df.to_csv(os.path.join(re_path, "result.csv"), index = false)

测试没有问题。

相关推荐
阿尔的代码屋2 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者19 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者19 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh21 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅21 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django