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

测试没有问题。

相关推荐
郑州光合科技余经理21 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12321 小时前
matlab画图工具
开发语言·matlab
dustcell.21 小时前
haproxy七层代理
java·开发语言·前端
norlan_jame21 小时前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054961 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再1 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
QQ5110082851 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
QQ_19632884751 天前
Python-flask框架西山区家政服务评价系统网站设计与开发-Pycharm django
python·pycharm·flask
遥遥江上月1 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js