django页面导出excel

from django.http import HttpResponse
from xlwt import *
from io import BytesIO
def excel_export(request):
    """
    导出excel表格
    """
    list_obj = Comment.objects.all().order_by("-time")
    if list_obj:
        # 创建工作薄
        ws = Workbook(encoding='utf-8')
        w = ws.add_sheet(u"数据报表第一页")
        w.write(, , "id")
        w.write(, , u"用户名")
        w.write(, , u"发布时间")
        w.write(, , u"内容")
        w.write(, , u"来源")
        # 写入数据
        excel_row =
        for obj in list_obj:
            data_id = obj.id
            data_user = obj.username
            data_time = obj.time.strftime(]
            data_content = obj.content
            dada_source = obj.source
            w.write(excel_row, , data_id)
            w.write(excel_row, , data_user)
            w.write(excel_row, , data_time)
            w.write(excel_row, , data_content)
            w.write(excel_row, , dada_source)
            excel_row +=
        # 检测文件是够存在
        # 方框中代码是保存本地文件使用,如不需要请删除该代码
        ###########################
        exist_file = os.path.exists("test.xls")
        if exist_file:
            os.remove(r"test.xls")
        ws.save("test.xls")
        ############################
        sio = BytesIO()
        ws.save(sio)
        sio.seek()
        response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=test.xls'
        response.write(sio.getvalue())
        return response

请求指定链接并返回结果时出现 TypeError: string argument expected, got 'bytes'  错误

经过排查问题出现在使用StringIO的write方法上,用BytesIO替代StringIO即可解决问题

上一篇:(二十二)java小练习三


下一篇:老李分享:Android性能优化之内存泄漏2