如何获取Excel文件的所有sheets名称
- ExcelFile
import pandas as pd
xl = pd.ExcelFile(filename)
xl.sheet_names
xl.parse(sheet_name)
ExcelFile使用xlrd模块,将表格类型的数据解析为pandas的数据框实例。参数填写文件路径或者缓存即可,其sheet_names属性就是所有sheet的名称。parse函数可以获取指定的某个sheet。
- read_excel的sheet_name参数
help(pd.read_excel)
------------------------------------------------------------------------------------------
sheet_name : string, int, mixed list of strings/ints, or None, default 0
Strings are used for sheet names, Integers are used in zero-indexed
sheet positions.
Lists of strings/integers are used to request multiple sheets.
Specify None to get all sheets.
str|int -> DataFrame is returned.
list|None -> Dict of DataFrames is returned, with keys representing
sheets.
Available Cases
* Defaults to 0 -> 1st sheet as a DataFrame
* 1 -> 2nd sheet as a DataFrame
* "Sheet1" -> 1st sheet as a DataFrame
* [0,1,"Sheet5"] -> 1st, 2nd & 5th sheet as a dictionary of DataFrames
* None -> All sheets as a dictionary of DataFrames
----------------------------------------------------------------------------------------------
df = read_excel(filename, sheet_name=None)
df.keys()
sheet_name参数可以为字符串、整数以及由整数、字符串组合成的列表或者None。默认为0,即返回第一个sheet。
当sheet_name为 str|int 时,直接返回DataFrame;
当sheet_name为 list|None时,返回DataFrame和sheet名称组成的字典。
所以直接将sheet_name设置为None,然后调用df.keys()可获取所有sheet的名称。