为django应用程序导出数据到excel时的ValueError

时间:2015-07-28 20:10:20

标签: python django excel

我正在尝试编写一些代码,将一些数据从网站导出到Excel工作表。这是我尝试使用Django重写整个网站的一部分。下面是我为导出编写的脚本。

def national_proposal_export_xlsx(modeladmin, request, queryset):
    import openpyxl
    from openpyxl.cell import get_column_letter
    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=conference_proposals_export.xlsx'
    wb = openpyxl.Workbook()
    ws = wb.get_active_sheet()
    ws.title = "Conference_proposals"

    row_num = 0

    columns = [
        (u"Master", 15),
        (u"Code", 15),
        (u"Title", 70),
        (u"Begin Time", 15),
        (u"End Time", 15),
        (u"Event type", 15),
        (u"Status", 15),
        # (u"Published", 15),
        # (u"Up to date", 15),
    ]

    for col_num in range(len(columns)):
        c = ws.cell(row=row_num + 1, column=col_num + 1)
        c.value = columns[col_num][0]
        # c.style.font.bold = True
        ws.column_dimensions[get_column_letter(col_num+1)].width = columns[col_num][1]

    for obj in queryset:
        row_num += 1
        row = [
            obj.master,
            obj.code,
            obj.title,
            obj.begin_time,
            obj.end_time,
            obj.event_type,
            obj.status,
            # obj.published,
            # obj.up_to_date,
        ]

        for col_num in range(len(row)):
            c = ws.cell(row=row_num + 1, column=col_num + 1)
            c.value = row[col_num]
            c.style.alignment.wrap_text = True

    wb.save(response)
    return response

但由于某种原因,我收到以下错误:

ValueError at /admin/events/nationalconferenceproposal/ Cannot convert 9000476 | TEST SESSION 001 (draft) to Excel Request Method: POST Request URL: http://localhost:8000/admin/events/nationalconferenceproposal/ Django Version: 1.7.3 Exception Type: ValueError Exception Value:
Cannot convert 9000476 | TEST SESSION 001 (draft) to Excel Exception Location: /Users/dthota/Code/venvs/planning/lib/python3.4/site-packages/openpyxl/cell/cell.py in _bind_value, line 217 Python Executable: /Users/dthota/Code/venvs/planning/bin/python Python Version: 3.4.3

它表示在最后一个for循环中错误是c.value = row[col_num]。但我无法理解!

1 个答案:

答案 0 :(得分:0)

我知道这是一个老问题,但我只是在努力解决类似的问题。对我来说,解决方案是将行[col_num]强制转换为string:

c.value = str(row[col_num])

请注意,数据随后将作为文本保存在Excel工作簿中,因此如果您要对数据进行计算等,则可能需要其他内容。