【问题标题】:Python Pandas - loop through folder of Excel files, export data from each Excel file's sheet into their own .xlsx filePython Pandas - 遍历 Excel 文件的文件夹,将每个 Excel 文件工作表中的数据导出到它们自己的 .xlsx 文件中
【发布时间】:2021-06-09 12:21:03
【问题描述】:

我有一个 Excel 文件文件夹,其中许多有 3-4 个选项卡的数据,我只希望这些数据作为单独的 Excel 文件。例如,假设我有一个包含三个选项卡的 Excel 文件:“员工”、“摘要”和“数据”。我希望它从中创建 3 个新的 Excel 文件:employees.xlsx、summary.xlsx 和 data.xlsx。

我的代码将遍历文件夹并识别所有选项卡,但我一直在努力弄清楚如何将数据从每张工作表单独导出到其自己的 Excel 文件中。我已经到了可以遍历文件夹、打开每个 Excel 文件并找到每个工作表的名称的地步。这是我目前所拥有的。

import pandas as pd
import os

# filenames
files = os.listdir()    
excel_names = list(filter(lambda f: f.endswith('.xlsx'), files))

excels = [pd.ExcelFile(name, engine='openpyxl') for name in excel_names]
sh = [x.sheet_names for x in excels] # I am getting all of the sheet names here
for s in sh:
    for x in s:
        #there is where I want to start exporting each sheet as its own spreadsheet

#df.to_excel("output.xlsx", header=False, index=False) #I want to eventually export it obviously, this is a placeholder

【问题讨论】:

  • 这需要使用 Python 来完成吗?使用 VBA 可以轻松完成。
  • 在这种特殊情况下,它确实需要在 Python 中完成。 VBA 可能更实用,但涉及到组织规则的故事就很长了,我就不多说了。

标签: python excel pandas dataframe export-to-excel


【解决方案1】:
import pandas as pd
import glob

# get the file names using glob 
# (this assumes that the files are in the current working directory)
excel_names = glob.glob('*.xlsx')
# iterate through the excel file names
for excel in excel_names:
    # read the excel file with sheet_name as none
    # this will create a dict
    dfs = pd.read_excel(excel, sheet_name=None)
    # iterate over the dict keys (which is the sheet name)
    for key in dfs.keys():
        # use f-strings (only available in python 3) to assign 
        # the new file name as the sheet_name
        dfs[key].to_excel(f'{key}.xlsx', index=False)

【讨论】:

  • 谢谢,我收到 xlrd.biffh.XLRDError: Excel xlsx file;不支持错误。有没有办法使用 openpyxl 而不是 XLRD 来做到这一点?我没有与 Glob 合作太多,所以我不知道我是否可以更改此设置。
  • @tenebrissilentio 你用的是什么版本的熊猫? print(pd.__version__) 代码的pd.read_excel(...) 部分是否抛出了错误?
  • 显然版本太旧了。我更新了 Pandas,它起作用了。我认为在 7 个月的过程中,更新 Pandas 不可能是问题,但天哪,我错了。做到了。非常感谢。
  • @tenebrissilentio 不客气,祝你好运。
猜你喜欢
  • 2021-10-09
  • 2015-09-27
  • 2016-10-28
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多