Search code examples
pythonxlrd

Getting Values Out of XLRD in Python


Is there any way to get strings out of excel spreadsheets with XLRD? I'm handling data with Electricity Meters, and the ID number of the meters keeps being returned out as a float, with a ".0" on the end. It has forced me to a halt, so if anyone has any ideas, that would be really helpful!

Thanks!


Solution

  • Assuming i have excel data as shown below electrical.xlsx

    The code which i can write to check if there is any float data type present. If it is present, then convert to string.

    import xlrd
    
    book = xlrd.open_workbook('electrical.xlsx')
    sheet = book.sheet_by_index(0)
    data = []
    for row in range(0, sheet.nrows):
        l = []
        for column in range(0, sheet.ncols):
            val = sheet.cell(row, column).value
            if isinstance(val,float):
                l.append(int(val))
            else:
                l.append(val)
    
        data.append(l)
    
    print(data) # [['Meter ID', 'value'], ['id101', '1'], ['id102', '2'], ['id103', '3']]