表格处理:多表格汇总(pandas)

之前写过一个帖子,也是完成多表格汇总的功能,用的方法是 xlrd,xlsxwriter。然后老师们留言说 pandas 处理该问题会更方便快捷。便去学习了一下,然后打开了新世界的大门,嘻嘻嘻,下面我们就来一起学习下吧。

使用的测试表仍是和上期一样的火影调查表。

表格处理:多表格汇总(pandas)
表格处理:多表格汇总(pandas)

新建了 3 张测试表格,result 作为结果表

表格处理:多表格汇总(pandas)

然后下面贴代码:

import pandas as pd
import os

# 将excel中的sheet名称放入列表
sheet_names = ["木叶","晓"]
# 将excel文件名称放入列表
path = r'D:\depthsdata\test'
xlsx_names = [x for x in os.listdir(path) if x.endswith(".xlsx")]
print(xlsx_names)
file_paths = []
for xlsx_name in xlsx_names:
    file_path = path + "\\" + xlsx_name
    file_paths.append(file_path)
print(file_paths)

writer = pd.ExcelWriter(r'D:\depthsdata\test\result.xlsx',engine='openpyxl')

num = 1
for sheet_name in sheet_names:
    df = None
    for file_path in file_paths:
        _df = pd.read_excel(file_path, sheet_name=sheet_name)
        if df is None:
            df = _df
        else:
            df = pd.concat([df, _df], ignore_index=True)
    # 下面的保存文件处填写writer,结果会不断地新增sheet,避免循环时被覆盖
    df.to_excel(excel_writer=writer, sheet_name=sheet_name, encoding="utf-8", index=False)
    print(sheet_name + "  保存成功!共%d个,第%d个。" % (len(sheet_names),num))
    num += 1
writer.save()
writer.close()

结果表显示如图:

表格处理:多表格汇总(pandas)

表格处理:多表格汇总(pandas)

师者诚不欺我,感谢。