Home > Net >  Read this Excel sheet OR that sheet in Python Pandas
Read this Excel sheet OR that sheet in Python Pandas

Time:09-25

There is an Excel workbook file, and there can be a sheet called "Purple" or "Blue", but there would never be a case where it has sheets with both names. There are a number of unrelated excel sheets in this file. How would you change the sheet_name = condition below to account for this?

import pandas as pd

tempTable = pd.read_excel(os.path.join(r, 'random_file.xlsx'), 
                                       sheet_name='Blue', 
                                       header=10, 
                                       nrows=10)

CodePudding user response:

Not very elegant solution but should work

def read_sheet(sheet_name):
    return pd.read_excel(os.path.join(r, 'random_file.xlsx'), 
                         sheet_name=sheet_name, 
                         header=10, 
                         nrows=10)
tempTable = None
try:
    tempTable = read_sheet('Blue')
except ValueError:
    tempTable = read_sheet('Purple')
  • Related