2024-06-24 13:27:20 发布
网友
我习惯用以下方式创建电子表格:
wbk = xlwt.Workbook() earnings_tab = wbk.add_sheet('EARNINGS') wbk.save(filepath)
有没有办法不将文件保存到文件路径,而是动态地将其写入下载文件的用户?或者我需要将其保存为tmp文件,然后将其提供给用户?
这是我在Django使用的:
response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=file.xls' book.save(response) return response
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()
引用the documentation for the ^{} method of ^{}:
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.
StringIO
修改示例:
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
有些人可能建议您使用cStringIO,而不是StringIO,但请注意,上次检查时cStringIO不能正确处理Unicode。
cStringIO
值得注意的是,Python 3中的StringIO被io替换。
io
这是我在Django使用的:
引用the documentation for the ^{} method of ^{} :
修改示例:
有些人可能建议您使用
cStringIO
,而不是StringIO
,但请注意,上次检查时cStringIO
不能正确处理Unicode。值得注意的是,Python 3中的
StringIO
被io
替换。相关问题 更多 >
编程相关推荐