xlwt write excel sheet on the fly

前端 未结 3 1011
太阳男子
太阳男子 2021-01-17 11:07

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

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


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 11:16

    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:

    import StringIO
    
    f = StringIO.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.

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

提交回复
热议问题