新版Pandas使用以下界面加载Excel文件:

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

但如果我不知道有哪些床单呢?

例如,我正在工作的excel文件,如下表

数据1,数据2…,数据N, foo, bar

但我不知道先验的N。

有没有办法从熊猫的excel文档中获得表的列表?


当前回答

#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
                                      

其他回答

如果你:

关注业绩 在执行时不需要文件中的数据。 想要使用传统的库还是使用自己的解决方案

下面是一个~10Mb的xlsx, xlsb文件的基准测试。

xls, xlsx

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)

注:

这是一个很好的资源 http://www.python-excel.org/ XLRD从2020年起不再维持

我尝试过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的xlsx文件上,有4张纸) 熊猫,xlrd: 12秒 Openpyxl: 24秒 建议方法:0.4秒

因为我的要求只是读取表名,读取整个时间的不必要开销让我很困扰,所以我选择了这种方法。

如果你读excel文件

dfs = pd.ExcelFile('file')

然后使用

dfs.sheet_names
dfs.parse('sheetname')

另一种变体

df = pd.read_excel('file', sheet_name='sheetname')

With the load_workbook readonly option, what was earlier seen as a execution seen visibly waiting for many seconds happened with milliseconds. The solution could however be still improved. import pandas as pd from openpyxl import load_workbook class ExcelFile: def __init__(self, **kwargs): ........ ..... self._SheetNames = list(load_workbook(self._name,read_only=True,keep_links=False).sheetnames) The Excelfile.parse takes the same time as reading the complete xls in order of 10s of sec. This result was obtained with windows 10 operating system with below package versions C:\>python -V Python 3.9.1 C:\>pip list Package Version --------------- ------- et-xmlfile 1.0.1 numpy 1.20.2 openpyxl 3.0.7 pandas 1.2.3 pip 21.0.1 python-dateutil 2.8.1 pytz 2021.1 pyxlsb 1.0.8 setuptools 49.2.1 six 1.15.0 xlrd 2.0.1

从excel (xls)中检索表名的最简单方法。, xlsx)为:

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

然后,要读取和存储特定工作表的数据(例如,工作表名称为“Sheet1”,“Sheet2”等),请输入“Sheet2”,例如:

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