Pandas:查找Excel文件中工作表列表

284

新版Pandas使用以下接口来加载Excel文件:

read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])

但是如果我不知道可用的工作表怎么办?

例如,我正在处理以下工作簿的Excel文件:

Data 1, Data 2 ..., Data N, foo, bar

但我事先不知道 N 是多少。

是否有一种方法可以在Pandas中从Excel文档中获取工作表列表?

12个回答

490
你仍然可以使用ExcelFile类(以及sheet_names属性):
xl = pd.ExcelFile('foo.xls')

xl.sheet_names  # see all sheet names

xl.parse(sheet_name)  # read a specific sheet to DataFrame

查看解析文件的文档以获取更多选项...


9
在此之前提到过这里,但我想保留一个DataFrame字典,使用{sheet_name: xl.parse(sheet_name) for sheet_name in xl.sheet_names} - Andy Hayden
2
希望我能给你更多的赞,这个方法也适用于多个版本的pandas!(不知道为什么他们喜欢经常改变API)感谢你指出parse函数,这是当前链接:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.ExcelFile.parse.html - Ezekiel Kruglick
2
打开 xlsx 文件时,在 pandas 1.1.5 中会失败。但是可以通过使用 xl = pd.ExcelFile('foo.xls', engine='openpyxl') 进行修复。查看与我的问题有关的内容,请参阅此线程 - vjangus

85
你应该明确指定第二个参数(sheetname)为None。就像这样:
 df = pandas.read_excel("/yourPath/FileName.xlsx", None);

"df"作为一个DataFrame字典,你可以通过运行以下代码来验证:

df.keys()

像这样的结果:

[u'201610', u'201601', u'201701', u'201702', u'201703', u'201704', u'201705', u'201706', u'201612', u'fund', u'201603', u'201602', u'201605', u'201607', u'201606', u'201608', u'201512', u'201611', u'201604']

请参考Pandas文档获取更多详情:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html


4
这段代码不必要地将每个工作表解析为DataFrame,这并非必须。"如何读取xls/xlsx文件"是另一个问题 - Andy Hayden
13
如果你关心所有的表格或者不介意额外的开销,这可能不是最有效的方法,但可能是最好的方法。 - CodeMonkey
2
命名参数称为 sheet_name。即,df = pandas.read_excel("/yourPath/FileName.xlsx", sheet_name=None, engine='openpyxl') - Corey Levinson

20

从Excel(xls,xlsx)中检索工作表名称的最简单方法是:

tabs = pd.ExcelFile("path").sheet_names 
print(tabs)

读取并存储特定工作表的数据(例如,假设工作表名称为“Sheet1”,“Sheet2”等),以“Sheet2”为例:

data = pd.read_excel("path", "Sheet2") 
print(data)

14

这是我发现的最快的方法,受@divingTobi答案的启发。基于xlrd、openpyxl或pandas的所有答案对我来说都很慢,因为它们都首先加载整个文件。

from zipfile import ZipFile
from bs4 import BeautifulSoup  # you also need to install "lxml" for the XML parser

with ZipFile(file) as zipped_file:
    summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]


5
#It will work for Both '.xls' and '.xlsx' by using pandas

import pandas as pd
excel_Sheet_names = (pd.ExcelFile(excelFilePath)).sheet_names

#for '.xlsx' use only  openpyxl

from openpyxl import load_workbook
excel_Sheet_names = (load_workbook(excelFilePath, read_only=True)).sheet_names
                                      

1
我相信该方法被称为“sheetnames”(没有下划线)。 - StudentAtLU

4
如果您:
  • 关心性能
  • 执行时不需要文件中的数据。
  • 希望使用常规库而不是自己编写解决方案

以下内容在一个大约10Mb的xlsxxlsb文件上进行了基准测试。

xlsx,xls

from openpyxl import load_workbook

def get_sheetnames_xlsx(filepath):
    wb = load_workbook(filepath, read_only=True, keep_links=False)
    return wb.sheetnames

基准测试: ~ 14倍速度提升

# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

xlsb

from pyxlsb import open_workbook

def get_sheetnames_xlsb(filepath):
  with open_workbook(filepath) as wb:
     return wb.sheets

基准测试: ~ 56倍的速度提升

# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

注意:


3
如果你读取Excel文件。
dfs = pd.ExcelFile('file')

然后使用。
dfs.sheet_names
dfs.parse('sheetname')

另一个变体
df = pd.read_excel('file', sheet_name='sheetname')

3

在 @dhwanil_shah 的回答基础上,您不需要提取整个文件。使用 zf.open 可以直接从一个压缩文件中读取内容。

import xml.etree.ElementTree as ET
import zipfile

def xlsxSheets(f):
    zf = zipfile.ZipFile(f)

    f = zf.open(r'xl/workbook.xml')

    l = f.readline()
    l = f.readline()
    root = ET.fromstring(l)
    sheets=[]
    for c in root.findall('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheets/*'):
        sheets.append(c.attrib['name'])
    return sheets

连续的两个readline看起来有些不清爽,但实际上只需要在第二行文本中获取内容,无需解析整个文件。

这种解决方案似乎比read_excel版本快得多,并且很可能也比完全提取版本更快。


1
不,.xls是完全不同的文件格式,所以我不认为这段代码会起作用。 - divingTobi

3

我尝试过xlrd、pandas、openpyxl等库,但随着文件大小的增加,它们似乎都需要指数级的时间来读取整个文件。上面提到的其他解决方案中使用“on_demand”的方式对我不起作用。如果你只想最初获取工作表名称,以下函数适用于xlsx文件。

def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],
                'name': sheet['@name']
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

由于所有的xlsx文件都是基本上被压缩的文件,我们直接提取底层XML数据并从工作簿中直接读取工作表名称,与库函数相比,这只需要几分之一秒的时间。
基准测试:(对于一个大小为6MB且有4个sheet的xlsx文件) Pandas, xlrd: 12秒 openpyxl: 24秒 建议方法:0.4秒
由于我的需求仅仅是读取工作表名称,读取整个文件所带来的不必要开销一直困扰着我,因此我选择了这种方法。

你正在使用哪些模块? - Daniel
@Daniel,我只使用了内置模块zipfile和用于将XML转换为易于迭代的字典的xmltodict。虽然您可以查看@divingTobi下面的答案,其中您可以在不实际提取文件的情况下阅读同一文件。 - Dhwanil shah
当我使用read_only标志尝试使用openpyxl时,速度显着提高(对于我的5 MB文件快了200倍)。load_workbook(excel_file).sheetnames 平均需要8.24秒,而 load_workbook(excel_file, read_only=True).sheetnames 平均只需要39.6毫秒。 - flutefreak7

2
from openpyxl import load_workbook

sheets = load_workbook(excel_file, read_only=True).sheetnames

我正在使用一个5MB的Excel文件,使用load_workbook而不加上read_only标记需要8.24秒。如果加上read_only标记,只需要39.6毫秒。如果你仍然想使用Excel库而不是采用xml解决方案,那么这种方法比解析整个文件的方法要快得多。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接