从模型中读取django数据并使用xlsxwriter编写它

时间:2016-09-08 15:25:32

标签: django python-2.7 xlsxwriter

我需要从我拥有的模型(称为Aged)中提取所有数据并触发一个函数将其导出为.xls文件。我发现xlsxWriter不确定我是否在正确的路径中,有没有办法可以调用我的完整模型并将其写入文件?

这就是我在views.py上的内容:

def writetoexcel(Reportdata):
    output = StringIO.StringIO()
    workbook = xlsxwriter.Workbook('Reporte3a4.xlsx', 
                                   {'constant_memory': True})
    worksheet = workbook.add_worksheet()

    bold = workbook.add_format({'bold': True})

    worksheet.write('A1', 'Priority', bold)
    worksheet.write('B1', 'PO Number', bold)

    Reporte = Reporte3a5.objects.all()

    row = 1
    col = 0

    for data in Reporte:
        worksheet.write(row, col, data.secondary_priority)
        worksheet.write(row, col + 1, data.po_number)
        worksheet.write(row, col + 2, data.ctb_status)

    workbook.close()
    xlsx_Data = output.getvalue()
    return  xlsx_Data

1 个答案:

答案 0 :(得分:2)

我对自己的问题得到了答案,这只是我使用的其他模型:

def xlsx(request):
    # Create a workbook and add a worksheet.
    output = io.BytesIO()
    workbook = xlsxwriter.Workbook(output, {'in_memory': True})
    worksheet = workbook.add_worksheet('Reporte3a5')
    bold = workbook.add_format({'bold': True})
    # Some data we want to write to the worksheet.
    reporte = Reporte3a5.objects.all() #my model

    # Start from the first cell. Rows and columns are zero indexed.
    row = 1
    col = 0

    # Iterate over the data and write it out row by row.
    for linea in reporte:
        worksheet.write(row, col, linea.df_status)
        worksheet.write(row, col + 1, linea.aged)
        worksheet.write(row, col + 2, linea.ship_set)
        row += 1

    # Write the title for every column in bold
    worksheet.write('A1', 'Priority', bold)
    worksheet.write('B1', 'Code', bold)

    workbook.close()

    output.seek(0)
    response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response['Content-Disposition'] = "attachment; filename=Reporte3a5.xlsx"

    return response

使用此功能,您将在同一页面中自动下载文件。