Search code examples
pythonexcelflaskxlrd

Flask Uploads reading an xlsx file without saving it


I'd like to upload an excel file in my web app, read the contents of it and display some cells. So basically I don't need to save the file as it's a waste of time.

Relevant code:

if form.validate_on_submit():

        f = form.xml_file.data.stream

        xml = f.read()

        workbook = xlrd.open_workbook(xml)

        sheet = workbook.sheet_by_index(0)

I can't wrap my mind around this as I keep getting filetype errors no matter what I try. I'm using Flask Uploads, WTF.file and xlrd for reading the file.

Reading the file works okay if I save it previously with f.save


Solution

  • To answer my own question, I solved it with

    if form.validate_on_submit():
    
            # Put the file object(stream) into a var
            xls_object = form.xml_file.data.stream
    
            # Open it as a workbook
            workbook = xlrd.open_workbook(file_contents=xls_object.read())