Trying to read in an series of xls files. They aren't formatted in a uniform manner. Sometimes the sheets exist, sometimes they don't. Sometimes they have one name, sometimes another. It's an imperfect world.
Some code I've tried to check for the sheet name:
import xlrd
wb=xlrd.open_workbook(r'C:\sample.xls')
class Workbook_Reading:
def __init__(self, wb):
self.wb = wb
self.history = None
def purch_hist(self):
if self.wb.sheet_loaded('Purchase History') is True:
purchase_history = wb.sheet_by_name('Purchase History')
self.history = purchase_history
elif self.wb.sheet_loaded('Previous Purchases') is True:
purchase_history = wb.sheet_by_name('Previous Purchases')
self.history = purchase_history
else:
pass
I keep getting an error: xlrd.bffh.XLRDError: No Sheet Named <'Purchase History'>
. I am testing this one a wb that I know specifically doesn't have the first condition (purchase history sheet), but has the other (previous purchases sheet). What did I do wrong?
This might help
import xlrd
class Workbook_Reading:
def __init__(self, wb):
self.history = None
self.desiredSheetNames = ['Purchase History', 'Previous Purchases']
self.availableSheetNames = []
self.wb = xlrd.open_workbook(r'C:\\sample.xls')
self.set_available_sheets()
def set_available_sheets(self):
for sheetName in self.desiredSheetNames:
try:
sheet = self.wb.sheet_by_name(sheetName)
self.availableSheetNames.append(sheetName)
except:
pass
def purch_hist(self):
if 'Purchase History' in self.availableSheetNames:
purchase_history = wb.sheet_by_name('Purchase History')
self.history = purchase_history
elif 'Previous Purchases') in self.availableSheetNames:
purchase_history = wb.sheet_by_name('Previous Purchases')
self.history = purchase_history
else:
pass