利用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)

测试没有问题。

相关推荐
虾球xz20 分钟前
CppCon 2018 学习:EFFECTIVE REPLACEMENT OF DYNAMIC POLYMORPHISM WITH std::variant
开发语言·c++·学习
Allen_LVyingbo25 分钟前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
小哈龙29 分钟前
裸仓库 + Git Bash 搭建 本地 Git 服务端与客户端
开发语言·git·bash
智能砖头33 分钟前
LangChain 与 LlamaIndex 深度对比与选型指南
人工智能·python
不坑老师42 分钟前
利用不坑盒子的Copilot,快速排值班表
microsoft·word·powerpoint·excel·copilot·wps
G探险者1 小时前
《如何在 Spring 中实现 MQ 消息的自动重连:监听与发送双通道策略》
java·开发语言·rpc
weixin_437398212 小时前
转Go学习笔记
linux·服务器·开发语言·后端·架构·golang
StrongerIrene2 小时前
rs build 的process.env的值undefined解决方案
开发语言·javascript·ecmascript
风逸hhh2 小时前
python打卡day58@浙大疏锦行
开发语言·python
让我们一起加油好吗2 小时前
【C++】list 简介与模拟实现(详解)
开发语言·c++·visualstudio·stl·list