我试图在 Django 网站上生成一个 excel 文件,所以我搜索了它并查看了 this example .我只编写一个函数,将我需要的内容写入 Excel 文件;
def create_excel(personal_information):
output = StringIO.StringIO()
book = xlsxwriter.Workbook(output)
sheet = book.add_worksheet()
if personal_information['name']:
sheet.write(1, 1, personal_information['name'], text_format)
book.close()
output.seek(0)
return output
在我看来.py;
def export(request):
personal_information = json.loads(request.POST.get('personal_data'))
output = create_excel(personal_information)
response = HttpResponse(output.read(), content_type="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename=Excel.xls'
return response
然而,这给出了“无”。你有什么办法解决我的问题吗?
谢谢。
最佳答案
试试这个: 在你的函数 create_excel 中:
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
.... your code .....
at the end of your function
# close workbook
workbook.close()
xlsx_data = output.getvalue()
return xlsx_data
在你看来:
if request.method == 'POST':
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment;
filename=your_template_name.xlsx'
xlsx_data = create_excel()
response.write(xlsx_data)
关于python - Django HttpResponse Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35991033/