【问题标题】:How to count the total number of sheets in an Excel file using Python如何使用 Python 计算 Excel 文件中的工作表总数
【发布时间】:2018-11-29 17:07:19
【问题描述】:

我正在使用 python 读取一个 excel 文件。

import pandas as pd
import os

xls = pd.ExcelFile('D:\DirectoryProject\Mapping.xlsx')

它有几个我不知道的数据表。如何使用 Python 计算 Mapping.xlsx 文件中的工作表总数?

【问题讨论】:

    标签: python excel pandas openpyxl xlrd


    【解决方案1】:

    openpyxl

    import openpyxl
    
    wb = openpyxl.load_workbook('file.xlsx') 
    res = len(wb.sheetnames)
    

    pandas

    import pandas as pd
    
    xl = pd.ExcelFile('file.xlsx')
    res = len(xl.sheet_names)
    

    xlrd

    import xlrd
    
    # use on_demand=True to avoid loading worksheet data into memory
    wb = xlrd.open_workbook('file.xlsx', on_demand=True)
    res = len(wb.sheet_names())  # or wb.nsheets
    

    【讨论】:

    • 可以将其标记为已回答吗,它可以工作并且对我来说很简单(python)
    【解决方案2】:

    只是为了补充上一个答案-

    len(pd.read_excel(r"D:\DirectoryProject\Mapping.xlsx", sheet_name="None"))
    

    这样你也可以得到张数。

    【讨论】:

    • 此解决方案有效,但它涉及在计算工作表数量之前将所有工作表读入内存(通过字典)。因此,它显得有点矫枉过正。
    • 是的,在这种情况下,我们可以使用您在回答中提到的 xlrd 的 on_demand 选项
    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多