【Day7】使用Django 产生 excel报表

之前因为可能因为需要使用收集的资料作分析,所以做了一个使用 Django来生成excel档案的功能,程序码如下

def excel_export(request):
    """
    汇出excel表格
    """
    list_obj = MachineParameters.objects.all().order_by("id")
    if list_obj:
        # 建立工作薄
        ws = Workbook(encoding='utf-8')
        w = ws.add_sheet(u"sheet1")
        w.write(0, 0, u"id")
        w.write(0, 1, u"Oil_Temp_Current_Val")
        #中间跳过
        w.write(0, 7, u"OilTempCurrentValPhase5")
        w.write(0, 8, u"totalGoodProductionNumber")
        # 写入资料
        excel_row = 1
        for obj in list_obj:
            data_id = obj.id
            Oil_Temp_Current_Val = obj.Oil_Temp_Current_Val
            totalProductionNumber = obj.totalProductionNumber
            #中间跳过
            w.write(excel_row, 7, OilTempCurrentValPhase5)
            w.write(excel_row, 8, totalGoodProductionNumber)
            excel_row += 1
        # 检测档案是够存在
        # 方框中程序码是储存本地档案使用,如不需要请删除该程序码
        ###########################
        exist_file = os.path.exists("test.xls")
        if exist_file:
            os.remove(r"test.xls")
        ws.save("test.xls")
        ############################
      
        output = BytesIO()
        ws.save(output)
        output.seek(0)
        response = HttpResponse(output.getvalue(), content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=MachineParameters.xls'
        response.write(output.getvalue())
        return response

这个功能基本算是直接 copy 内容农场的程序码, 没办法,功能方面刚好符合我的需求
使用来源:python (django)汇出资料库中的资讯为excel表格
这边有稍微进阶一点的,有兴趣可以参考一下。
django 一键生成excel表格并下载到本地,并根据时间删除档案,上传excel档案
有时候内容农场的技术文也真的能帮上点忙就是了。


<<:  寝室的秘密授课(三):测试案例 Test Case

>>:  Day9 Git

从 JavaScript 角度学 Python(7) - 条件与回圈

前言 接下来是聊条件与回圈的部分,毕竟写程序这两个东西非常常使用到。 条件控制 条件控制的语法又可以...

【Day 06】从零开始的 Line Chatbot-浅谈 Django

前几天在做建立专案的时候,好像看到一个不是很懂的东西-Django。 今天不谈 Chatbot,我们...

ASP.NET MVC 从入门到放弃(Day23)-MVC编辑资料介绍

接下来讲讲编辑 部分... 在查询的View那边可以看到下方程序码 @Html.ActionLink...

My experience with Customer Obsession

Clients’ satisfaction is the priority while achiev...

Day 09 - Type Signature

yo, what's up? 到目前为止,目前我们把最基本的概念 pure function, cu...