如何从XLS文件中获取工作表名称而不加载整个文件?

问题描述 投票:0回答:11

我目前正在使用 pandas 读取 Excel 文件并向用户显示其工作表名称,以便他可以选择他想要使用的工作表。问题是文件非常大(70 列 x 65k 行),在笔记本上加载最多需要 14 秒(CSV 文件中的相同数据需要 3 秒)。

我在 panda 中的代码是这样的:

xls = pandas.ExcelFile(path)
sheets = xls.sheet_names

我之前尝试过xlrd,但得到了类似的结果。这是我使用 xlrd 的代码:

xls = xlrd.open_workbook(path)
sheets = xls.sheet_names

那么,有人可以建议一种比读取整个文件更快的方法来从 Excel 文件中检索工作表名称吗?

python excel pandas xlrd
11个回答
84
投票

您可以使用 xlrd 库并使用“on_demand=True”标志打开工作簿,这样工作表就不会自动加载。

您可以以与 pandas 类似的方式检索工作表名称:

import xlrd
xls = xlrd.open_workbook(r'<path_to_your_excel_file>', on_demand=True)
print xls.sheet_names() # <- remeber: xlrd sheet_names is a function, not a property

20
投票

根据我对标准/流行库的研究,截至 2020,尚未针对

xlsx
/
xls
实施此操作,但您可以针对
xlsb
执行此操作。无论哪种方式,这些解决方案都应该给您带来巨大的性能改进。对于
xls
xlsx
xlsb

以下是在 ~10Mb

xlsx
xlsb
文件上进行的基准测试。

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)

备注:


18
投票

我尝试过 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'], # can be @sheetId for some versions
                'name': sheet['name'] # can be @name
            }
            sheets.append(sheet_details)

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

由于所有 xlsx 基本上都是压缩文件,因此我们提取底层 xml 数据并直接从工作簿中读取工作表名称,与库函数相比,这只需几分之一秒的时间。

基准测试:(在包含 4 张的 6mb xlsx 文件上)
熊猫,xlrd: 12 秒
openpyxl: 24 秒
建议方法: 0.4 秒


3
投票

通过将@Dhwanil shah的答案与here的答案相结合,我编写的代码也与只有一张纸的xlsx文件兼容:

def get_sheet_ids(file_path):
sheet_names = []
with zipfile.ZipFile(file_path, 'r') as zip_ref:
    xml = zip_ref.open(r'xl/workbook.xml').read()
    dictionary = xmltodict.parse(xml)

    if not isinstance(dictionary['workbook']['sheets']['sheet'], list):
        sheet_names.append(dictionary['workbook']['sheets']['sheet']['@name'])
    else:
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_names.append(sheet['@name'])
return sheet_names

3
投票

基于 dhwanil-shah 的答案,我发现这是最有效的:


import os
import re
import zipfile

def get_excel_sheet_names(file_path):
    sheets = []
    with zipfile.ZipFile(file_path, 'r') as zip_ref: xml = zip_ref.read("xl/workbook.xml").decode("utf-8")
    for s_tag in  re.findall("<sheet [^>]*", xml) : sheets.append(  re.search('name="[^"]*', s_tag).group(0)[6:])
    return sheets

sheets  = get_excel_sheet_names("Book1.xlsx")
print(sheets)
# prints: "['Sheet1', 'my_sheet 2']"

xlsb 替代工作


import os
import re
import zipfile

def get_xlsb_sheet_names(file_path):
    sheets = []
    with zipfile.ZipFile(file_path, 'r') as zip_ref: xml = zip_ref.read("docProps/app.xml").decode("utf-8")
        xml=grep("<TitlesOfParts>.*</TitlesOfParts>", xml)
        for s_tag in  re.findall("<vt:lpstr>.*</vt:lpstr>", xml) : sheets.append(  re.search('>.*<', s_tag).group(0))[1:-1])

    return sheets


优点是:

  • 速度
  • 代码简单,易于适配
  • 不创建临时文件或目录(全部在内存中)
  • 仅使用核心库

待改进:

  • 正则表达式解析(不确定如果工作表名称包含双引号 ["] 会如何表现)

1
投票

传递完整路径库路径文件名的 Python 代码适配(例如,('c:\xml ile.xlsx'))。 来自 Dhwanil shah 的回答,没有使用 Django 方法来创建临时目录。

import xmltodict
import shutil
import zipfile


def get_sheet_details(filename):
    sheets = []
    # Make a temporary directory with the file name
    directory_to_extract_to = (filename.with_suffix(''))
    directory_to_extract_to.mkdir(parents=True, exist_ok=True)
    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(filename, '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 = 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'],  # can be sheetId for some versions
                'name': sheet['@name']  # can be name
            }
            sheets.append(sheet_details)
    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

1
投票

仅使用标准库:

import re
from pathlib import Path
import xml.etree.ElementTree as ET
from zipfile import Path as ZipPath


def sheet_names(path: Path) -> tuple[str, ...]:
    xml: bytes = ZipPath(path, at="xl/workbook.xml").read_bytes()
    root: ET.Element = ET.fromstring(xml)
    namespace = m.group(0) if (m := re.match(r"\{.*\}", root.tag)) else ""
    return tuple(x.attrib["name"] for x in root.findall(f"./{namespace}sheets/") if x.tag == f"{namespace}sheet")


1
投票

读取 Excel 工作表名称的简单方法:

import openpyxl
wb = openpyxl.load_workbook(r'<path-to-filename>') 
print(wb.sheetnames)

使用 pandas 从 Excel 中的特定工作表读取数据:

import pandas as pd
df = pd.read_excel(io = '<path-to-file>', engine='openpyxl', sheet_name = 'Report', header=7, skipfooter=1).drop_duplicates()

0
投票

XLSB 和 XLSM 解决方案。灵感来自 Cedric Bonjour。

import re
import zipfile

def get_sheet_names(file_path):
    with zipfile.ZipFile(file_path, 'r') as zip_ref: 
        xml = zip_ref.read("docProps/app.xml").decode("utf-8")
    xml = re.findall("<TitlesOfParts>.*</TitlesOfParts>", xml)[0]
    sheets = re.findall(">([^>]*)<", xml)
    sheets = list(filter(None,sheets))
    return sheets

0
投票

处理所有

xlsx
xlsm
xlsb
的简单解决方案可以进一步从 Cedric 的答案

得出

关于工作表名称中

"
(以及
<
>
&
)的使用,根据我有限的实验:

  • xlsx
    文件将
    "
    替换为
    &quot;
  • xlsx
    xlsm
    xlsb
    <
    替换为
    &lt;
    ,将
    >
    替换为
    &gt;
    ,并将
    &
    替换为
    &amp;

html.unescape
可以为我们解决所有这些问题,而且我们仍然只使用标准库。

调整我们的正则表达式以使用捕获组可以帮助简化我们的 python 语法。

虽然这在我的机器上可以进行有限的测试,但所有这些使用正则表达式来快速解析 xml 确实让我感到紧张。

import html
import re
import zipfile
from pathlib import Path


def _get_xlsx_names(file_path: Path) -> list[str]:
    with zipfile.ZipFile(file_path, "r") as zip_ref:
        xml = zip_ref.read("xl/workbook.xml").decode("utf-8")
    return [
        html.unescape(sheet_name)
        for sheet_name in re.findall(r'<sheet.*?name="([^"]+?)".*?/>', xml)
    ]


def _get_xlsm_names(file_path: Path) -> list[str]:
    with zipfile.ZipFile(file_path, "r") as zip_ref:
        xml = zip_ref.read("docProps/app.xml").decode("utf-8")
    return [
        html.unescape(sheet_name)
        # Find all titles
        for titles in re.findall(r"<TitlesOfParts>(.+?)</TitlesOfParts>", xml)
        # Find all sheet names in titles
        for sheet_name in re.findall(r"<vt:lpstr>(.+?)</vt:lpstr>", titles)
    ]


def get_sheet_names(file_path: str | Path) -> list[str]:
    file_path = Path(file_path)
    if file_path.suffix == ".xlsx":
        return _get_xlsx_names(file_path)
    if file_path.suffix in [".xlsm", ".xlsb"]:
        return _get_xlsm_names(file_path)
    msg = f"Unsupported file extension '{file_path.suffix}' found."
    raise NotImplementedError(msg)

-4
投票

您也可以使用

data=pd.read_excel('demanddata.xlsx',sheet_name='oil&gas')
print(data)   

这里的demanddata是你的文件名 石油和天然气是您的工作表名称之一。假设您的工作表中可能有 n 个工作表。只需在 Sheet_name="您所需工作表的名称" 处给出您要获取的工作表的名称即可

© www.soinside.com 2019 - 2024. All rights reserved.