python XLRD库如何扫描excel中的所有工作表?



我计划使用XLRD库来读取我导入的excel文件中的行数和列数。

我使用了下面的代码,它们工作得很好。

import xlrd
path = 'sample123.xlsx'
inputWorkbook = xlrd.open_workbook(path)
inputWorksheet = inputWorkbook.sheet_by_index(0)
print("Your worksheet has: " + str(inputWorksheet.nrows) + " rows")
print("Your worksheet has: " + str(inputWorksheet.ncols) + " columns")

然而,这些代码只对一个工作表(第一个)运行。如果我想随机导入一些excel文件,但我不知道每个文件的总索引或表名,是否有编码建议,以便扫描该文件中的所有表,从而检测所有表的行数和列数?

非常感谢您的帮助。

然而,这些代码只对一个表(第一个)运行

那是因为你在调用getsheet方法时传递了index=0…

调用方法get_sheet

myDoc.get_sheet(index)

其中index是表的索引,如果你不知道它,你可以通过名称找到它:

sheet_names().index(nameOfMySheet)

这里的doc

下面是一个关于如何在工作簿中获取工作表的示例

import xlrd
book = xlrd.open_workbook("sample.xls")
for sheet in book.sheets():
print sheet.name

使用xlrd从一个excel文件中读取所有的工作表,

import xlrd
path = 'sample123.xlsx'
inputWorkbook = xlrd.open_workbook(path)
dict_sheet_tabs= {} # Store sheets in a dictionary
for sheet_name in inputWorkbook.sheet_names():
print(sheet_name ) # name of each tab
all_sheet = wb1.sheet_by_name(sheet_name) # read sheet by name
dict_sheet_tabs.update({sheet_name:all_sheet })
print(dict_sheet_tabs)
>>> {'sheet_name1': <xlrd.sheet.Sheet object at 0x7fa903b6efd0>, 'sheet_name2': <xlrd.sheet.Sheet object at 0x7fa9038ece10>}
#The dictionary keys are sheet names and values are the sheet content 

最新更新