Search code examples
pythonxlwt

xlwt write excel sheet on the fly


I am used to creating a spreadsheet in the following way:

    wbk = xlwt.Workbook()
    earnings_tab = wbk.add_sheet('EARNINGS')
    wbk.save(filepath)

Is there any way to not save to file to a filepath, and instead write it on-the-fly to a user who downloads the file? Or do I need to save it as a tmp file and then serve that to the user?


Solution

  • To quote the documentation for the .save() method of xlwt:

    It can also be a stream object with a write method, such as a StringIO, in which case the data for the excel file is written to the stream.

    Modified example:

    from io import StringIO  # instead of Python 2.x `import StringIO`
    
    f = StringIO() # create a file-like object 
    
    wbk = xlwt.Workbook()
    earnings_tab = wbk.add_sheet('EARNINGS')
    
    wbk.save(f) # write to stdout
    

    Some may suggest you use cStringIO instead of StringIO, but be forewarned that cStringIO when last I checked does not properly handle Unicode.

    Important Update

    It's perhaps also worth noting that StringIO is replaced in Python 3 by io.

    The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

    source

    So use:

    from io import StringIO
    # instead of import StringIO