Home » excel » python – DictReader for Excel-Files

python – DictReader for Excel-Files

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a file that I currently save to csv but it’s originally an Excel-file (Excel 2010).

Its content is of this sort:

Name;Category;Address
McFood;Fast Food;Street 1
BurgerEmperor;Fast Food;Way 1
BlueFrenchHorn;French;Street 12
PetesPizza;Italian;whatever
SubZero;Fast Food;Highway 6

I save it as csv to being able to parse it. At the moment I use DictReader (here is the code and a corresponding question)

Is there something like the DictReader available for an Excel-module like xlrd?
How would I have to change my code?

How to&Answers:

Posted this as an answer to potentially help those looking for a similar solution. There is a gist on github (not mine) that contains a potential solution. Might need a few tweaks to apply to your particular situation: Github Gist

For those who do not wish to click, here is the code:

try:
    import xlrd
    import mmap

    def XLSDictReader(f, sheet_index=0):
        data    = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
        book    = xlrd.open_workbook(file_contents=data)
        sheet   = book.sheet_by_index(sheet_index)

        def item(i, j):
            return (sheet.cell_value(0,j), sheet.cell_value(i,j))

        return ( dict(item(i,j) for j in range(sheet.ncols)) \
                     for i in range(1, sheet.nrows) )

except ImportError:
    XLSDictReader = None