首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django HttpResponse Excel

Django HttpResponse Excel
EN

Stack Overflow用户
提问于 2016-03-14 23:02:53
回答 2查看 6.7K关注 0票数 3

我试图在Django网站上生成一个excel文件,所以我搜索了它,并查看了this example。我编写了一个简单的函数,将我需要的内容写入Excel文件;

代码语言:javascript
复制
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

在我的view.py中;

代码语言:javascript
复制
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

然而,这给出了“无”。你有什么办法解决我的问题吗?

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2018-02-07 17:08:50

试试这个:在你的函数create_excel中:

代码语言:javascript
复制
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

在您的视图中:

代码语言:javascript
复制
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)
票数 2
EN

Stack Overflow用户

发布于 2020-05-20 23:43:32

我有几个解决方案。我有一个在views.py文件下执行此操作的demo project。我使用openpyxl,但如果您需要保留宏(.xlsm),也可以使用其他库,如xlwings

下面是我的代码片段:

代码语言:javascript
复制
def export_data(request):
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="Data.xlsx"'

    # create workbook
    wb = Workbook()
    sheet = wb.active

    # stylize header row
    # 'id','title', 'quantity','pub_date'

    c1 = sheet.cell(row = 1, column = 1) 
    c1.value = "id"
    c1.font = Font(bold=True)

    c2 = sheet.cell(row= 1 , column = 2) 
    c2.value = "title"
    c2.font = Font(bold=True)

    c3 = sheet.cell(row= 1 , column = 3) 
    c3.value = "quantity"
    c3.font = Font(bold=True)

    c4 = sheet.cell(row= 1 , column = 4) 
    c4.value = "pub_date"
    c4.font = Font(bold=True)

    # export data to Excel
    rows = models.Data.objects.all().values_list('id','category', 'quantity','pub_date',)
    for row_num, row in enumerate(rows, 1):
        # row is just a tuple
        for col_num, value in enumerate(row):
            c5 = sheet.cell(row=row_num+1, column=col_num+1) 
            c5.value = value

    wb.save(response)

    return response
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35991033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档