數據庫數據導出CSV文件,瀏覽器下載


直接上代碼:

def download(request):
    # 從數據庫查詢數據
    data_list = Info.objects.all()

    # 定義返回對象
    response = HttpResponse()
    # 給返回對象定義解析類型
    response['Content-Type'] = 'csv'
    # 聲明一個csv的響應
    response['Content-Disposition'] = 'attachment;filename="data.csv"'
    # csv的響應編碼格式聲明
    response.write(codecs.BOM_UTF8)

    # 把響應設置成文件句柄
    writer_obj = csv.writer(response)
    # 先寫入表格頭
    writer_obj.writerow(["姓名", "年齡", "地址"])
    # 寫入數據
    for info in data_list:
        writer_obj.writerow([info.name, info.age, info.address])

    return response

參考1:

https://www.cnblogs.com/haoshine/p/5695760.html

import csv
import codecs
import datetime
from django.db import connection
from django.contrib.auth.models import User
from django.http import HttpResponse
from models import *

def output(request, user_id, node_id, function_id):
    function_id = int(function_id)
    user_id = int(user_id)
    node_id= int(node_id)

    # 指定csv請求回應
    response = HttpResponse(content_type='text/csv')


    user = User.objects.get(id=user_id)
    functions_has_permission = DataPermission.objects.filter(category=node_id)

    # 取出sql語句
    function_obj = DataPermission.objects.get(id=function_id)
    function_obj_sql = function_obj.sql

    # 執行sql語句,並執行。保存執行結果和字段名
    cursor = connection.cursor()
    cursor.execute(function_obj_sql)
    results = cursor.fetchall()

    descriptions = cursor.description
    descriptions_long = len(descriptions)
    description_list = [None] * descriptions_long
    i = 0
    for description in descriptions:
        description_list[i] = description[0]
        i = i + 1

    # 將執行結果從元組形式轉化為列表形式。
    i=0
    results_long = len(results)
    results_list = [None] * results_long
    for i in range(results_long):
        results_list[i] = list(results[i])
    # print(results_list)

    # 為文件取名字
    now = datetime.datetime.now()
    now = str(now.isoformat())
    name = (now + '.csv').replace(':', '')

    # 聲明一個csv的響應
    response['Content-Disposition'] = 'attachment; filename="%s"' % name
    # csv的響應的編碼格式聲明
    response.write(codecs.BOM_UTF8)
    writer = csv.writer(response)

    # 轉碼問題
    a = u''
    for result in results_list:
        i=0
        for item in result:
            if type(item) == type(a):
                # 如果是unicode類型,那么編碼成utf-8
                result[i] = item.encode('utf-8')
            i = i + 1
    # with open(response, 'wb') as f:
    writer.writerow(description_list)
    for result in results_list:
        writer.writerow(result)
        i = i + 1
    response.close()
    return response  
參考

 

導出的文件,中文如果顯示成亂碼

解決方法:將上面代碼中的'utf-8' 改成 'gb2312'

result[i] = item.encode('gb2312')

 

參考2:

抽取數據庫文件:
 
def exportmysql(request):
     conn= MySQLdb.connect(
     host='192.168.137.3',
     port = 3306,
     user='root',
     passwd='1234567',
     db ='DEVOPS',
     charset='UTF8'
     )
     cur = conn.cursor()
     a = cur.execute("select ip,info,env from machine_info")
     info = cur.fetchall()
     response = HttpResponse(content_type='text/csv')
     response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
     writer = csv.writer(response)
     for row in info:
        writer.writerow(row)
     return response

 

參考3:

最近一個用django開發的web項目要進行數據的導入導出,所以有必要了解下。

     django中主要用HttpResponse將請求結果返回給瀏覽器,所以文件的下載也是通過改對象進行處理的,具體的一個列子的代碼如下:

[python] view plain copy
#文件下載  
def download(request):  
    """                                                                           
    Send a file through Django without loading the whole file into                
    memory at once. The FileWrapper will turn the file object into an             
    iterator for chunks of 8KB.                                                   
    """   
      
    #讀取mongodb的文件到臨時文件中  
    fileid_=request.GET["fileid"]  
    filepath_ = ('%s/%s'%(MEDIA_ROOT, fileid_)) #文件全路徑  
    file_=TFiles.objects.get(fileid=int(fileid_))  
    filename_=file_.filename  
    filetype_=file_.filetype  
  
    if os.path.isfile(filepath_):  
        pass  
    else:  
        mongoLoad(fileid_)  
      
    #下載文件  
    def readFile(fn, buf_size=262144):#大文件下載,設定緩存大小  
        f = open(fn, "rb")  
        while True:#循環讀取  
            c = f.read(buf_size)  
            if c:  
                yield c  
            else:  
                break  
        f.close()  
    response = HttpResponse(readFile(filepath_), content_type='APPLICATION/OCTET-STREAM') #設定文件頭,這種設定可以讓任意文件都能正確下載,而且已知文本文件不是本地打開  
    response['Content-Disposition'] = 'attachment; filename='+filename_.encode('utf-8') + filetype_.encode('utf-8')#設定傳輸給客戶端的文件名稱  
    response['Content-Length'] = os.path.getsize(filepath_)#傳輸給客戶端的文件大小  
    return response 

 

=====================

Python+Django實現文件的下載

HttpResponse,  StreamingHttpResponse,  FileResponse

https://blog.csdn.net/li627528647/article/details/77544136


免責聲明!

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



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