1. 程式人生 > >python (django)匯出資料庫中的資訊為excel表格

python (django)匯出資料庫中的資訊為excel表格

from django.http import HttpResponse
from xlwt import *
from StringIO import StringIO  #需要stringIO,這是python2中的,如果是python3,使用 from io import StringIO
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(0, 0, "id")
        w.write(0, 1, u"使用者名稱")
        w.write(0, 2, u"釋出時間")
        w.write(0, 3, u"內容")
        w.write(0, 4, u"來源")
        # 寫入資料
        excel_row = 1
        for obj in list_obj:
            data_id = obj.id
            data_user = obj.username
            data_time = obj.time.strftime("%Y-%m-%d")[:10]
            data_content = obj.content
            dada_source = obj.source
            w.write(excel_row, 0, data_id)
            w.write(excel_row, 1, data_user)
            w.write(excel_row, 2, data_time)
            w.write(excel_row, 3, data_content)
            w.write(excel_row, 4, dada_source)
            excel_row += 1
        # 檢測檔案是夠存在
        # 方框中程式碼是儲存本地檔案使用,如不需要請刪除該程式碼
        ###########################
        exist_file = os.path.exists("test.xls")
        if exist_file:
            os.remove(r"test.xls")
        ws.save("test.xls")
        ############################
        sio = StringIO()  #這裡原部落格是StringIO.StringIO(),發現有點問題
        ws.save(sio)
        sio.seek(0)
        response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=yourname.xls'
        response.write(sio.getvalue())
        return response