python查询数据库导出csv文件_数据库数据导出CSV文件,浏览器下载

直接上代码:

defdownload(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 indata_list:

writer_obj.writerow([info.name, info.age, info.address])return response

参考1:

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

ContractedBlock.gif

ExpandedBlockStart.gif

importcsvimportcodecsimportdatetimefrom django.db importconnectionfrom django.contrib.auth.models importUserfrom django.http importHttpResponsefrom models import *

defoutput(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=0for description indescriptions:

description_list[i]=description[0]

i= i + 1

#将执行结果从元组形式转化为列表形式。

i=0

results_long=len(results)

results_list= [None] *results_longfor i inrange(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 inresults_list:

i=0for item inresult: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 inresults_list:

writer.writerow(result)

i= i + 1response.close()return response

参考

导出的文件,中文如果显示成乱码

解决方法:将上面代码中的'utf-8' 改成 'gb2312'

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

参考2:

抽取数据库文件:defexportmysql(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 ininfo:

writer.writerow(row)return response

参考3:

最近一个用django开发的web项目要进行数据的导入导出,所以有必要了解下。

django中主要用HttpResponse将请求结果返回给浏览器,所以文件的下载也是通过改对象进行处理的,具体的一个列子的代码如下:

[python] view plain copy#文件下载

defdownload(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_.filetypeifos.path.isfile(filepath_):pass

else:

mongoLoad(fileid_)#下载文件

def readFile(fn, buf_size=262144):#大文件下载,设定缓存大小

f = open(fn, "rb")while True:#循环读取

c =f.read(buf_size)ifc:yieldcelse:breakf.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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值