xlwt write excel sheet on the fly

你说的曾经没有我的故事 提交于 2019-12-01 14:16:55

问题


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?


回答1:


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.




回答2:


this is what i use in Django:

response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=file.xls'
book.save(response)
return response



回答3:


class QueryToExcel(object):
def __init__(self, doc_name = 'doc_name'):
    #some set up stuff
    self.b_io = BytesIO()
    self.workbook = pd.ExcelWriter(self.b_io, engine='xlsxwriter')
    self.run() #fill in workbook with pandas dataframes
    self.workbook.save()

def get_workbook(self):
    return self.b_io.getvalue()


app = Flask(__name__)
app.debug = True 
@app.route('/pvh/', methods = ['GET'])
def get_workbook(self):
    return self.b_io.getvalue()


来源:https://stackoverflow.com/questions/15649034/xlwt-write-excel-sheet-on-the-fly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!