python - Django HttpResponse Excel

标签 python django python-2.7 xlsxwriter

我试图在 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/

相关文章:

django - 如何让 Django Graphene ModelForm Mutation 应用

python - pandas dataframe切片产生不同的结果

html - 异常值 : string indices must be integers : Render bundle error vue + django

python - 具有排列签名的堆算法

python - 尝试在用 Python 编写的 Tropo 应用程序中创建简单的本地语法

python - 如何使用 BeautifulSoup 抓取分页表并将结果存储在 csv 中?

python - 如何从 Django 模型生成文档?

Python:访问外部进程信息

python - 如何在 cgi/python 中将列表的列表写入文件?

python - 当用户提供某个关键字作为输入时结束函数