Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xlwt write excel sheet on the fly

Tags:

python

xlwt

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?

like image 269
David542 Avatar asked Mar 26 '13 23:03

David542


People also ask

How do you write data in Excel sheet using Python XLWT?

Using xlwt module, one can perform multiple operations on spreadsheet. For example, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work.

How do I read and write an Excel file using Python xlrd?

Read Excel File in PythonThe command need to be installed is xlrd module. xlrd module is used to extract data from a spreadsheet. After writing the above code (Read Excel File in Python), Ones you will print then the output will appear as a “ Name ”. Here, row 0 and column 0 data is extracted from the spreadsheet.

How do I merge cells in Excel with XLWT?

There are two methods on the Worksheet class to do this, write_merge and merge . merge takes existing cells and merges them, while write_merge writes a label (just like write ) and then does the same stuff merge does. Both take the cells to merge as r1, r2, c1, c2 , and accept an optional style parameter.


1 Answers

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
like image 171
mechanical_meat Avatar answered Sep 28 '22 06:09

mechanical_meat