martes, 14 de junio de 2011

Leer datos de Excel con Python

Para mi PFC necesito leer datos directamente de ficheros Excel. He encontrado una librería que nos facilita la tarea: xlrd.

Dicha librería sólo sirve para tareas de lectura. Si queremos escribir existe otra equivalente, que en este caso se llama xlwt.

Ambas son compatibles con ficheros Excel 97, 2000, XP y 2003.

Para abrir una archivo de Excel, basta con hacer:

excel = xlrd.open_worbook("hoja.xls")

Ahora podemos seleccionar una hoja por su nombre:

hoja = excel.sheet_by_name("hoja 1")

Aunque también podríamos hacerlo por índices.

Dejo un ejemplo completo con las funciones más básicas:


import xlrd


''' Return a xlrd.sheet object with the Excel sheet information.
   
    Arguments:
    filename -- Location of Excel file.
    sheetname -- The name of the Excel page ie:"Testing".
'''
def open_xls(filename,sheetname):
    # Open the workbook
    wb = xlrd.open_workbook(filename,formatting_info=True)
   
    # Select the sheet
    sh = wb.sheet_by_name(sheetname)
   
    # Returns the sheet
    return sh


''' Returns a list of ParetoFront individuals fitness in with format
    [Obj1Fitness,Obj2Fitness].
   
    Arguments:
    sheet -- The Excel sheet returned from open_xls() function.
    iteration -- The iteration to obtain the Pareto Front.
'''
def get_pf(sheet,iteration):
    ind_fitness = list()
   
    # Iterate through rows
    for rownum in range(sheet.nrows):
        # Select only individuals in given iteration
        if sheet.cell_value(rownum,0) == iteration:
            # Save [Obj1NSGA2,Obj2NSGA2] of PF individuals
            if sheet.cell_xf_index(rownum,1) != sheet.cell_xf_index(rownum,2):
                ind_fitness.append([sheet.cell_value(rownum,5),sheet.cell_value(rownum,4)])
   
    return ind_fitness
           
   
def main():
    sheet = open_xls("BestsFinal.xls","Training")
    print get_pf(sheet,2)

    return 0

if __name__ == '__main__':
    main()

No hay comentarios:

Publicar un comentario