如何使用python从文件夹中的多个excel文件中读取包含“mine”的工作表名称的任何工作表?我正在使用xlrd。
dir_to_load = "C:\\Users\\User\\Desktop\\"
dir_to_save = "C:\\Users\\User\\Desktop\\"
file_name = "Test.xlsx"
os.chdir(dir_to_load)
wb= xlrd.open_workbook(file_name)
ws = wb.sheet_by_index(-1)
out_list = []
我知道我只是阅读一个文件并获取最后一张,但我想要从多个文件中包含或LIKE%Mine%的工作表。感谢。
答案 0 :(得分:0)
以下解决方案基于使用函数get_worksheet_names(spreadsheet_name)
来获取电子表格中每个工作表的名称:
import xlrd
# Utility function to get worksheet names from a spreadsheet:
def get_worksheet_names(spreadsheet_name):
worksheets = xlrd.open_workbook(spreadsheet_name).sheet_names()
worksheet_names = []
for j in worksheets:
worksheet_names.append(worksheets.sheet_by_name(j))
return worksheet_names
# Here is your original code, modified:
dir_to_load = "C:\\Users\\User\\Desktop\\"
dir_to_save = "C:\\Users\\User\\Desktop\\"
file_name = "Test.xlsx"
os.chdir(dir_to_load)
wsnames = get_worksheet_names(file_name)
for name in wsnames:
if 'mine' in name: # change to whatever search criteria you'd like here
print name
(关于术语的说明:Microsoft uses "workbook" and "spreadsheet" interchangeably,但我更喜欢"电子表格"因为每个人都知道这意味着什么,而#34;工作簿"更加含糊不清。)