python 保存excel 文件


1,python 將數據庫信息到處為excel。

使用模塊xlwt,配合django

def excel_export(request):
    """
    導出excel表格
    """
    list_obj = Student.objects.all()
    if list_obj:
        # 創建工作薄
        ws = Workbook(encoding='utf-8')
        w = ws.add_sheet(u"學生表")
        w.write(0, 0, "學號")
        w.write(0, 1, u"姓名")
        w.write(0, 2, u"性別")
        w.write(0, 3, u"出生日期")
        # 寫入數據
        excel_row = 1
        for obj in list_obj:
            data_id = obj.sno
            data_user = obj.sname
            data_sex = obj.ssex
            data_birthday = obj.sbirthday.strftime("%Y-%m-%d")
            # obj.sbirthday.strftime("%Y-%m-%d")
            w.write(excel_row, 0, data_id)
            w.write(excel_row, 1, data_user)
            w.write(excel_row, 2, data_sex)
            w.write(excel_row, 3, data_birthday)
            excel_row += 1
        # 方框中代碼是保存本地文件使用,如不需要請刪除該代碼
        ###########################
        exist_file = os.path.exists("test.xls")
        if exist_file:
            os.remove(r"test.xls")
        ws.save("test.xls")
        ############################
        import io
        output = io.BytesIO()
        ws.save(output)
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=test.xls'
        response.write(output.getvalue())
        return response

2,直接通過前端調用配置接口就自動下載excel文件了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM